检查字符串中是否存在多个单词之一?

Check if one of multiple words exists in the string?

我有这样的字符串:

$str = "it is a test";

我想检查这些词:ittest。我想要 returns true 如果字符串中至少有 个单词。

这是我所做的:(虽然它不起作用)

$keywords = array ('it', 'test');
if(strpos($str, $keywords) !== false){ echo 'true';}
else echo 'false';

我该怎么做?

最简单的方法是使用 explode 函数,如下所示:

$str = "it is a test"; // Remember your quotes!

$keywords = array ('it', 'test');

$str_array = explode(" ", $str);
$foundWords = [];
foreach ($keywords as $key)
{
    if (in_array($key, $str_array))
    {
        $foundWords[] = $key;
    }
}
foreach($foundWords as $word)
{
    print("Word '{$word}' was found in the string '{$str}'<br />");
}

这也是打印的功能

这给了我结果:

Word 'it' was found in the string 'it is a test'
Word 'test' was found in the string 'it is a test'

我认为您的代码存在问题,它试图将整个数组与字符串匹配,请尝试在 foreach 循环中执行此操作。

另一种方式是:

$keywords = array ('it', 'test');
echo (strpos($srt, $keywords[0]) ? "true" : "false");
echo (strpos($srt, $keywords[1]) ? "true" : "false");

使用 preg_match() 进行简单检查,您可以在模式中添加许多不同的单词,只需在单词之间使用分隔符 |

以下将匹配部分单词,因此将匹配更大的单词,如 pittestifyitinerary。该模式也区分大小写,因此 ItTest 将不会匹配。

$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表示单词边界,所以它只会匹配确切的单词。

我不确定,很抱歉我错了。 我认为 strpos 不适用于数组?

尝试做:

$array = ('it', 'test');
for($i=0;$i<$array.length;$i++){

//here the strpos Method but with $array[$i] }