使用正则表达式:
\b
匹配一个单词边界,用它来匹配整个单词
- 使用标志
i
执行不区分大小写的匹配
像这样匹配每个单词:
function stopWords($string, $stopwords) {
foreach ($stopwords as $stopword) {
$pattern = '/\b' . $stopword . '\b/i';
if (preg_match($pattern, $string)) {
return true;
}
}
return false;
}
$stopwords = array('fuc', 'dic', 'pus');
$bad = stopWords('confucius', $stopwords); // true
$bad = stopWords('what the Fuc?', $stopwords); // false
一个较短的版本,灵感来自对这个问题的回答:确定一个字符串是否包含数组中的一组单词中的一个,用于implode
创建一个大表达式:
function stopWords($string, $stopwords) {
$pattern = '/\b(' . implode('|', $stopwords) . ')\b/i';
return preg_match($pattern, $string) > 0;
}