preg_match for multiple words
Asked Answered
J

4

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?

Jumbled answered 13/3, 2012 at 18:1 Comment(0)
H
28

Something like:

preg_match_all('#\b(rain|dry|clear)\b#', $string, $matches);
Hatchel answered 13/3, 2012 at 18:7 Comment(2)
@Autolycus I was going to add a space \s around the words, but then I noticed you already used a word boundary \b.Hatchel
@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.Hatchel
D
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.

Dewees answered 13/3, 2012 at 18:8 Comment(1)
That 'i' for ignore case helped!Soissons
S
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."

Snipe answered 13/3, 2012 at 18:11 Comment(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.Epicurean
M
1
preg_match('\brain\b',$string, $matches);
var_dump($matches);
Minette answered 13/3, 2012 at 18:3 Comment(1)
Missing delimiters, and doesn't return more than one valueHuebner

© 2022 - 2024 — McMap. All rights reserved.