9

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?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Asim Zaidi
  • 27,016
  • 49
  • 132
  • 221

4 Answers4

28

Something like:

preg_match_all('#\b(rain|dry|clear)\b#', $string, $matches);
jeroen
  • 91,079
  • 21
  • 114
  • 132
  • @Autolycus I was going to add a space `\s` around the words, but then I noticed you already used a word boundary `\b`. – jeroen Mar 13 '12 at 18:13
  • @Autolycus The `#` at the beginning and end mark the beginning and end of the regex and are necessary (that or any other character) so that you can add switches at the end, like `#i` for case insensitive matching. – jeroen Mar 13 '12 at 18:14
5
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.

Czechnology
  • 14,832
  • 10
  • 62
  • 88
2

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

Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
Pave
  • 2,347
  • 4
  • 21
  • 23
  • 1
    `strpos()` and `strstr()` do not offer word boundaries. This answer shows why the asker's approach fails, but it does not offer a resolving technique. This answer should have been a comment under the question. – mickmackusa Aug 05 '22 at 00:22
1
preg_match('\brain\b',$string, $matches);
var_dump($matches);
cetver
  • 11,279
  • 5
  • 36
  • 56