2

Hi I have to search two strings in one string. For example

$string = "The quick brown fox jumped over a lazy cat";
if($string contains both brown and lazy){
  then execute my code
}

I have tried pregmatch like this,

if(preg_match("/(brown|lazy)/i", $string)){
    execute my code
}

But it enters if loop if one of them is present in the string. But i want it enter the if condition only if both of the strings are present in the parent string. How can I achieve this.

NoTE: I don't want loop over the string. (just like explode the string and foreach over the exploded array and search using strpos)

Mad Angle
  • 2,347
  • 1
  • 15
  • 33
  • `$string contains both brown and lazy` Keyword here is: `and`. – Shomz Oct 30 '14 at 05:21
  • `$regex = "/(brown)[^.]*(lazy)/i";` much shorter. – Funk Forty Niner Oct 30 '14 at 05:24
  • If you were looking for a way to do it within the regex, this post explains how to get an 'and' effect with a regex lookahead: http://stackoverflow.com/questions/469913/regular-expressions-is-there-an-and-operator – Tim Oct 30 '14 at 05:24

2 Answers2

5

Try like

if(preg_match("/(brown)/i", $string) && preg_match("/(lazy)/i", $string)){
    execute my code
}

Yon can also try with strpos like

if(strpos($string, 'brown') >= 0 && strpos($string, 'lazy') >= 0){
    execute my code
}
GautamD31
  • 28,552
  • 10
  • 64
  • 85
  • Both your strpos examples were wrong: it will never return TRUE and `>0` would fail if the position is 0 (the beginning of the string). – Shomz Oct 30 '14 at 05:25
  • @Shomz yes I also came to know that.Thanks for the suggestion – GautamD31 Oct 30 '14 at 05:26
  • No, it won't, it should work with zero as well. `>= 0` if you don't like `!== FALSE` that much. – Shomz Oct 30 '14 at 05:26
  • 1
    OMG!!..How could I forgot this simple logic to use an AND Operator. Thanks @Gautam3164. Its simply rocks. I chose the first one. – Mad Angle Oct 30 '14 at 05:36
3

Late answer, in case you wish to test for an exact match on both words:

$regex= "/\b(brown)\b[^.]*\b(lazy)\b/i";

$string = "The quick brown fox jumped over a lazy cat";

if(preg_match($regex, $string))

{
    echo 'True';
} else {
    echo 'False';
}

  • Or, replace it with $regex = "/(brown)[^.]*(lazy)/i"; if you don't want to test for an exact match, which is a much shorter method.
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141