首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >PHP检查字符串中是否至少包含两个特定的单词

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

Stack Overflow用户
提问于 2018-12-12 07:10:46
回答 2查看 1.1K关注 0票数 0

我使用preg_match检查字符串中是否有特定的单词:

代码语言:javascript
复制
$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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-12-12 07:40:04

您可以使用preg_match_all来完成此操作

代码语言:javascript
复制
$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
票数 0
EN

Stack Overflow用户

发布于 2018-12-12 07:53:33

如果你不关心精确匹配,那么选择的答案就可以了。如果你想精确匹配单词,那么你需要使用单词边界\b

示例如下:

代码语言:javascript
复制
$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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53733739

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档