首页 文章

使用stripos在PHP中检查错误的单词[复制]

提问于
浏览
0

这个问题与以下内容完全相同:

我在php中实现了这个“坏词”检查功能:

# bad word detector
function check_badwords($string) {
    $badwords = array(a number of words some may find inappropriate for SE);
    foreach($badwords as $item) {
        if(stripos($string, $item) !== false) return true;
    }
    return false;
}

它工作正常,除了我有一点问题 . 如果$ string是:

Who is the best guitarist ever?

...它返回true,因为与 Who ($ string)和 ho ($ badwords数组中)匹配 . 如何修改函数以便它只检查完整的单词,而不只是单词的一部分?

  • check_badwords('She is a ho'); //应该返回true

  • check_badwords('Who is she?'); //应该返回false

谢谢!

3 回答

  • 1

    为了检查完整的单词,你应该使用regular expressions

    function check_badwords($string)
    {
        $badwords = array(/* the big list of words here */);
        // Create the regex
        $re = '/\b('.implode('|', $badwords).')\b/';
        // Check if it matches the sentence
        return preg_match($re, $string);
    }
    

    How the regex works

    正则表达式以matches a word boundary的特殊序列 \b 开始和结束(即,当单词字符后跟非单词字符或反之时;单词字符是字母,数字和下划线) .

    在两个单词边界之间有一个subpattern,其中包含由 | 分隔的所有坏单词 . 子模式匹配任何坏词 .

    如果你想知道发现了什么坏词你可以改变功能:

    function check_badwords($string)
    {
        $badwords = array(/* the big list of words here */);
        $re = '/\b('.implode('|', $badwords).')\b/';
        // Check for matches, save the first match in $match
        $result = preg_match($re, $string, $match);
        // if $result is TRUE then $match[1] contains the first bad word found in $string
       return $result;
    }
    
  • 0

    您可能想用preg_match替换stripos

    如果你能使它成为更好的正则表达式,那么对你有更多的权力:

    preg_match("/\s($string){1}\s/", $input_line, $output_array);
    
  • 1

    您甚至可以小写$ string,然后使用stripos甚至是正则表达式,只需使用 in_array() . 这与整个单词相符 .

相关问题