0

I am a new person in the PHP. I have one String.I use this to find a word for strpos function for example..

$a= "google" ;
$b= "google is best one" ;

  if(strpos($b, $a) !== false) {
echo "true, " ; // Working Fine...

}

so i want to in this case check My Example

$a= "google,yahoo,Bing" ;
$b= "Bing is Good " ;

  if(strpos($b, $a) !== false) {
echo "true, " ; // I Need True...

}

This is how you do PHP

safvan saf
  • 43
  • 7

4 Answers4

0

To clarify, it looks like you're trying to perform a match such that any value in a list of values from $a is present in $b. This is not possible with a simple strpos() call because strpos() looks for the exact occurrence of the string you're passing in.

What you're attempting to do is a pattern-based search. To make this work, please look into using a regular expression with preg_match(). Such an example could look like this:

$pattern = '/google|yahoo|Bing/';
$target_string = 'Bing is good';

if(preg_match($pattern, $target_string)) {
    echo "true, ";
}

For more information, look into regular expression syntax and play around with it until you're familiar with how they work.

B. Fleming
  • 7,170
  • 1
  • 18
  • 36
  • I Need to `$pattern` with comma seprate ? – safvan saf Aug 06 '18 at 18:02
  • Please review regular expression syntax. For a regular expression to work, you need to use the pipe `|` character as a delimiter, not a comma `,`. If you only have a comma-separated list of values, then you need to transform the string using some kind of `str_replace()` call. – B. Fleming Aug 06 '18 at 18:07
0

Split the string on the comma using explode() and then check each of the parts individually:

$a= "google,yahoo,Bing" ;
$b= "Bing is Good " ;

$parts = explode(',', $a);

foreach ($parts as $part) {

    if(strpos($b, $part) !== false) {
        echo "true, " ; // I Need True...
    }

}
Marleen
  • 2,245
  • 2
  • 13
  • 23
0

Like Patrick Q said put names in an array example is here

becuase you are searching all three words "google,yahoo,Bing" which can not be true.

but for beginner to understand other way.

$a[0]= "google";
$a[1]= "yahoo";
$a[2]= "Bing";
$b= "Bing is Good";
strpos($b, $a[0]); // false
strpos($b, $a[1]); // false
strpos($b, $a[2]); // true as Bing found

also you can loop through to check

mortypk
  • 46
  • 1
  • 11
0

You can solve your issue with a regular expression:

if (preg_match('/string1|string2|string3/i', $str)){
  //if one of them found
}else{
  //all of them can not found
}
i alarmed alien
  • 9,412
  • 3
  • 27
  • 40