我实施了这个"坏词"检查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数组)匹配。如何修改函数以便它只检查完整的单词,而不只是单词的一部分?
谢谢!
答案 0 :(得分:1)
你可能想用preg_match替换stripos
如果你能使它成为更好的正则表达式,那么对你有更多的权力:
preg_match("/\s($string){1}\s/", $input_line, $output_array);
答案 1 :(得分: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);
}
regex
如何运作
正则表达式以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;
}
答案 2 :(得分:0)
你甚至可以小写$ string,然后使用stripos甚至是正则表达式,只需使用in_array()
。这与整个单词相符。