preg_match用于多个单词

Aut*_*cus 9 php

我想测试一个字符串,看它包含某些单词.

即:

$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);
Run Code Online (Sandbox Code Playgroud)

但该方法只匹配一个单词.如何检查多个单词?

jer*_*oen 20

就像是:

preg_match_all('#\b(rain|dry|clear)\b#', $string, $matches);
Run Code Online (Sandbox Code Playgroud)


Cze*_*ogy 5

preg_match('~\b(rain|dry|certain|clear)\b~i',$string);
Run Code Online (Sandbox Code Playgroud)

您可以|在正则表达式中将竖线字符()用作“或”。

如果您只需要知道是否有任何单词,请preg_match按上述方式使用。如果您需要匹配任何一个单词的所有出现,请使用preg_match_all

preg_match_all('~\b(rain|dry|certain|clear)\b~i', $string, $matches);
Run Code Online (Sandbox Code Playgroud)

然后检查$matches变量。