2012-03-13 116 views
8

我想测试一个字符串以查看它是否包含某些单词。preg_match用于多个单词

即:

$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); 

但该方法仅匹配一个字。我如何检查多个单词?

+3

preg_match_all() – 2012-03-13 18:02:17

+0

请参阅编辑的问题 – Autolycus 2012-03-13 18:05:33

回答

15

喜欢的东西:

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

是什么#\ S不 – Autolycus 2012-03-13 18:10:59

+0

@Autolycus我要添加一个空格'\ s'围绕这些单词,但是我注意到你已经使用了一个单词边界'\ b'。 – jeroen 2012-03-13 18:13:01

+0

@Autolycus开始和结束处的'#'标记正则表达式的开始和结束,并且是必需的(或其他任何字符),以便您可以在末尾添加开关,例如不区分大小写的匹配的'#i'。 – jeroen 2012-03-13 18:14:54

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

缺少分隔符,并且不返回多个值 – 2012-03-13 18:04:03

+0

请参阅编辑的问题 – Autolycus 2012-03-13 18:05:53

3
preg_match('~\b(rain|dry|certain|clear)\b~i',$string); 

您可以使用管道字符(|)的容器中 “或” 正则表达式。

如果您只需要知道是否存在任何字词,请使用上述preg_match。如果您需要匹配任何的话所有的出现次数,使用preg_match_all

preg_match_all('~\b(rain|dry|certain|clear)\b~i', $string, $matches); 

然后检查$matches变量。