If preg_match with a few words

Is it possible to use an if statement with preg_match for several words and make the condition true if all words are found?

  $line = "one blah, two blah blah three"; //not working code if (preg_match('[one|two|three]' , $line)) { echo "matched all three"; } else{ echo "didn't match all three"; } 

We tried a lot of things, but the conditional always occurs if at least one word is found.

+5
source share
2 answers

Using a positive view:

 preg_match("%(?=.*one)(?=.*two)(?=.*three)%", $line) 

EDIT: Explanation: (?=...) says "matches 0-length here if ... right away." So you can sketch it like this (with a slightly different original line to show a bit out of order):

 two blah, one blah blah three ----------=== found! === found! ------------------------===== found! 

(where --- - .* , and === is the search word). As each look matches, the matching position moves along the size of the match, but the lookahead match size is always 0, so it stays in place (at the beginning of the line) and allows the next view to look for the same space again.

+4
source

It might be more logical and efficient to use strpos to check if a string contains words, e.g.

 $line = "one blah, two blah blah three"; if (strpos($line, "one") !== false && strpos($line, "two") !== false && strpos($line, "three") !== false) { echo "matched all three"; } else { echo "didn't match all three"; } 

Example

+2
source

All Articles