PHP函数检查禁止的单词

时间:2014-02-12 16:25:11

标签: php function

我有这个功能来检查我的字符串中被禁止的单词。但是,如果删除空格,我无法检测禁止的单词 - 使该函数无用。有人可以帮助我改进它以检测没有空格的单词。

$string = "Hellomynameisuser.";
check_for_banned_words($string);

function check_for_banned_words($string){
    $badWords = array(
        "ban",
        "bad",
        "user",
        "pass",
        "stack",
        "name",
        "html"
    );
    $matches = array();
    $matchFound = preg_match_all(
        "/\b(" . implode($badWords,"|") . ")\b/i", 
        $string, 
        $matches
    );
    if($matchFound):
        $words = array_unique($matches[0]);
        echo("<ul>");
        foreach($words as $word):
            echo("<li>" . $word . "</li>");
        endforeach;
        echo("</ul>");
    endif;
}

1 个答案:

答案 0 :(得分:2)

\b检测字边界,删除它们以获得常规匹配。

"/(" . implode("|", $badWords) . ")/i",