PHP实现的敏感词过滤方法,以下是一份过滤敏感词的编码。有需要可以参考参考。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
function sensitive($list, $string){ $count = 0; $sensitiveWord = ''; $stringAfter = $string; $pattern = "/".implode("|",$list)."/i"; if(preg_match_all($pattern, $string, $matches)){ $patternList = $matches[0]; $count = count($patternList); $sensitiveWord = implode(',', $patternList); $replaceArray = array_combine($patternList,array_fill(0,count($patternList),'*')); $stringAfter = strtr($string, $replaceArray); } $log = "原句为 [ {$string} ]<br/>"; if($count==0){ $log .= "暂未匹配到敏感词!"; }else{ $log .= "匹配到 [ {$count} ]个敏感词:[ {$sensitiveWord} ]<br/>". "替换后为:[ {$stringAfter} ]"; } return $log; }
|
调用方法
1 2 3 4 5 6 7 8 9 10 11 12 13
| function testAction(){ $string = 'likeyou小白喜欢小黑爱着的大黄'; $list = ['小明', '小红', '大白', '小白', '小黑', 'me', 'you']; $result = $this->sensitive($list, $string); echo ($result); die;
}
|