Reputation: 28294
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?
Upvotes: 9
Views: 48042
Reputation: 91744
Something like:
preg_match_all('#\b(rain|dry|clear)\b#', $string, $matches);
Upvotes: 28
Reputation: 2428
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."
Upvotes: 2
Reputation: 14992
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.
Upvotes: 5