0

文字列に悪い単語があることがわかったときに true を返す関数を PHP で作成したいと考えています。

次に例を示します。

function stopWords($string, $stopwords) {
if(the words in the stopwords variable are found in the string) {
return true;
}else{
return false;
}

$stopwordsvariable は、次のような値の配列であると想定してください。

$stopwords = array('fuc', 'dic', 'pus');

どうやってやるの?

ありがとう

4

3 に答える 3

1

正規表現を使用します:

  • \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;
}
于 2012-02-04T22:03:39.850 に答える