I want to test a string to see it contains certain words.
i.e:
$string = "The rain in spain is certain as the dry on the plain is over and it is not clear";
preg_match('`\brain\b`',$string);
But that method only matches one word. How do I check for multiple words?
Something like:
preg_match_all('#\b(rain|dry|clear)\b#', $string, $matches);
http://php.net/manual/en/function.preg-match.php
"Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster."
preg_match('~\b(rain|dry|certain|clear)\b~i',$string);
You can use the pipe character (|
) as an "or" in a regex.
If you just need to know if any of the words is present, use preg_match
as above. If you need to match all the occurences of any of the words, use preg_match_all
:
preg_match_all('~\b(rain|dry|certain|clear)\b~i', $string, $matches);
Then check the $matches
variable.
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