Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_match for multiple words

Tags:

php

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?

like image 580
Asim Zaidi Avatar asked Mar 13 '12 18:03

Asim Zaidi


3 Answers

Something like:

preg_match_all('#\b(rain|dry|clear)\b#', $string, $matches);
like image 188
jeroen Avatar answered Sep 28 '22 16:09

jeroen


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."

like image 30
Pave Avatar answered Sep 28 '22 18:09

Pave


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.

like image 32
Czechnology Avatar answered Sep 28 '22 17:09

Czechnology