正規表現を使用します:
\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
して、1 つの大きな式を作成します。
function stopWords($string, $stopwords) {
$pattern = '/\b(' . implode('|', $stopwords) . ')\b/i';
return preg_match($pattern, $string) > 0;
}