我正在使用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
}
这工作得很好,但是如果至少有一个单词,它将返回true;如果该字符串中的数组中至少有两个单词,则我需要它返回true。
可以一步完成吗?如果没有,我应该从这里走哪条路来获得那个结果?
谢谢!:D
答案 0 :(得分:1)
您可以为此使用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
答案 1 :(得分:1)
如果您的要求是知道字符串中至少有 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个必需单词,则仅报告一个。
$string = 'This string contains a string and other stuff!';
答案 2 :(得分:0)
如果您不希望完全匹配,则所选答案很好。如果要匹配完全匹配的单词,则需要使用单词边界\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)