PHP 检查字符串中是否至少包含两个特定单词

PHP Check if a string has at least two specific words in it

我正在使用 preg_match 检查字符串中是否包含特定单词:

$string = 'This string contains a few words that are in an array!';
$arr = ['string', 'few', 'words'];

if(preg_match('['.implode('|', $arr).']', $string)){
    //do something if there is at least one word from the array inside that string
}

这工作得很好,但如果至少有一个单词,它将 return 为真,如果该字符串中的数组中至少有两个单词,我需要 return 为真.

可以一步完成吗?如果不是,我应该从这里走哪条路来获得那个结果?

谢谢!:D

你可以使用 preg_match_all 来完成这个

$string = 'This string contains a few words that are in an array!';
$arr = ['string', 'few', 'words'];
$count = preg_match_all('['.implode('|', $arr).']', $string); // Returns 3

如果您不在意完全匹配,则所选答案很好。如果你想匹配精确的单词,那么你需要使用单词边界 \b

示例如下:

$arr = ['string', 'few', 'words'];

preg_match_all('#\b('.implode('|', $arr).')\b#', $string, $wordsFound);

$wordsFound = array_unique($wordsFound[0]);

if(count($wordsFound) >= 2){
    echo "Matched";
}else{
    echo "Not matched";
}


Input: $string = 'This string contains a few words that are in an array!';
Output: Matched (3 founds)

Input: $string = 'This string222 contains a few words that are in an array!';
Output: Matched (2 founds)

Input: $string = 'This string222 contains a few23 words that are in an array!';
Output: Not Matched (1 found)

Input: $string = 'This string contains a string words that are in an array!';
Output: Matched (2 founds)

Input: $string = 'This string contains a string string that are in an array!';
Output: Not Matched (1 found)

如果您的要求是知道字符串中 至少 2 个所需的单词,那么您需要小心。如果您在字符串中有 2 个相同的单词,那么如果您只使用 preg_match_all 搜索出现次数,则很容易得到误报。

这将报告 3,即大海捞针中存在所有 3 个词

$string = 'This string contains a string and a few other words!';
$finds = ['string', 'few', 'words'];
$findCount = 0;

foreach ($finds as $find) {
    if ( strpos($string, $find) !== false ) $findCount++;
}
echo $findCount;

使用这个字符串会报2

$string = 'This string contains a string and a other words!';

最重要的是,如果您两次使用包含单词 string 的字符串,但没有使用 2 个所需单词,则仅报告 ONE

$string = 'This string contains a string and other stuff!';