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('她是个豪'); //应该返回真
  • check_badwords('她是谁?'); //应该返回false

谢谢!

4

3 回答 3

1

您可能想用 preg_match 替换 stripos

如果您可以使其成为更好的正则表达式,则对您有更大的影响:

preg_match("/\s($string){1}\s/", $input_line, $output_array);
于 2017-09-05T21:39:11.787 回答
1

为了检查完整的单词,您应该使用正则表达式

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);
}

regex工作原理

正则表达式以匹配单词边界的特殊序列开始和结束\b,当单词字符后跟非单词字符时,反之亦然;单词字符是字母、数字和下划线)。

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

如果您想知道发现了什么坏词,您可以更改函数:

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;
}
于 2017-09-05T22:02:29.177 回答
0

您甚至可以将 $string 小写,然后使用 stripos 甚至正则表达式,只需使用in_array(). 那将与整个单词匹配。

于 2017-09-05T22:17:03.737 回答