我有一个检查坏词的功能,但它没有按照我想要的方式工作。例如,test 是一个 cuss 词,那么如果我说"测试",该函数会将其计为一个 cuss 词。我将如何解决这个问题,以便它不会这样做。
这是我的代码:
function censor($message) {
$badwords = $this->censor; //array with the cuss words.
$message = @ereg_replace('[^A-Za-z0-9 ]','',strtolower(' '.$message.' '));
foreach($badwords as $bad) {
$bad = trim($bad);
if(strpos($message.' ', $bad.' ')!==false) {
if(strlen($bad)>=2) {
return true;
}
}
}
}
首先,ereg_replace
已从 PHP 5.3.0 开始被弃用。
现在,对于您的问题:您可以使用'b
作为单词边界。
简而言之:
'b
允许您使用'bword'b
形式的正则表达式。
有关更多详细信息,请参阅此页面。
你甚至可以使用下面我从 PHP preg_replace
文档的示例 2 复制的代码:
$string = 'The quickest brown fox jumped over the lazy dog.';
$patterns = array();
$patterns[0] = '/ quick /';
$patterns[1] = '/ brown /';
$patterns[2] = '/ fox /';
echo preg_replace($patterns, ' *** ', $string);
Output: The quickest *** *** jumped over the lazy dog.