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)

3
  • $string contains both brown and lazy Keyword here is: and. Commented Oct 30, 2014 at 5:21
  • $regex = "/(brown)[^.]*(lazy)/i"; much shorter. Commented Oct 30, 2014 at 5: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: stackoverflow.com/questions/469913/… Commented Oct 30, 2014 at 5:24

2 Answers 2

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
}
Sign up to request clarification or add additional context in comments.

4 Comments

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 yes I also came to know that.Thanks for the suggestion
No, it won't, it should work with zero as well. >= 0 if you don't like !== FALSE that much.
OMG!!..How could I forgot this simple logic to use an AND Operator. Thanks @Gautam3164. Its simply rocks. I chose the first one.
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.

3 Comments

Thanks @Fred -ii- for your concern:)
@BlankHead You're welcome. I was testing at the time and was away from this page while doing that, which explains my late answer. If that's your +1, thanks :)
Hey. No mention please. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.