我使用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
发布于 2018-12-12 07:40:04
您可以使用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
发布于 2018-12-12 07:53:33
如果你不关心精确匹配,那么选择的答案就可以了。如果你想精确匹配单词,那么你需要使用单词边界\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)
https://stackoverflow.com/questions/53733739
复制相似问题