Asim Zaidi
Asim Zaidi

Reputation: 28294

preg_match for multiple words

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

Answers (4)

jeroen
jeroen

Reputation: 91744

Something like:

preg_match_all('#\b(rain|dry|clear)\b#', $string, $matches);

Upvotes: 28

Pave
Pave

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

Czechnology
Czechnology

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

cetver
cetver

Reputation: 11829

preg_match('\brain\b',$string, $matches);
var_dump($matches);

Upvotes: 1

Related Questions