检测字符串中的禁止字

时间:2012-08-09 22:38:00

标签: php strpos

我有一个检查坏词的功能,但它不按我想要的方式工作。例如,测试是一个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;
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:2)

首先,从PHP 5.3.0开始,ereg_replace已被弃用。

现在,问题是:您可以使用\b作为单词边界。

  

简单地说:\b允许您使用执行“仅限全字”搜索   \bword\b

形式的正则表达式

有关详细信息,请参阅this page


您甚至可以使用下面的代码,我从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.