Is it possible to use an if statement with preg_match
for multiple words and to 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";
}
Have tried quite a few things but the conditional is always meet if even one word is found..
Using positive lookahead:
preg_match("%(?=.*one)(?=.*two)(?=.*three)%", $line)
EDIT: Explanation: (?=...)
says "match 0-length here if ...
is immediately following". Thus, you can sketch it like this (with a bit different original line to demonstrate the out-of-order bit):
two blah, one blah blah three
----------=== found!
=== found!
------------------------===== found!
(where ---
is .*
, and ===
is the sought word). As each lookahead matches, the matched position is advanced by match size - but match size of a lookahead is always 0, so it stays in place (at the start of the string) and allows for the next lookahead to search the same space again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With