我有这样一个字符串:
$str = "it is a test";
我想检查这些词:it
, test
。如果字符串中有至少其中一个单词,我希望它返回 true
。
这是我所做的:(虽然它不起作用)
$keywords = array ('it', 'test');
if(strpos($str, $keywords) !== false){ echo 'true';}
else echo 'false';
我该怎么做?
最佳答案
使用 preg_match()
进行简单检查,您可以在模式中添加许多不同的单词,只需在单词之间使用分隔符 |
。
下面会匹配部分词,所以像pit
、testify
、itinerary
这样的大词会被匹配。该模式还区分大小写,因此 It
和 Test
将不会匹配。
$str = "it is a test";
if (preg_match("/it|test/", $str))
{
echo "a word was matched";
}
抱歉,我不知道你在处理其他语言,你可以试试这个:
$str = "你好 abc efg";
if (preg_match("/\b(你好|test)\b/u", $str))
{
echo "a word was matched";
}
我还需要提到 \b
表示单词边界,因此它只会匹配确切的单词。
https://stackoverflow.com/questions/33653956/