1. 敏感词过滤方法
/ * @todo 敏感词过滤,返回结果 * @param array $list 定义敏感词一维数组 * @param string $string 要过滤的内容 * @return string $log 处理结果 */ 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} ]
"; if($count==0){ $log .= "暂未匹配到敏感词!"; }else{ $log .= "匹配到 [ {$count} ]个敏感词:[ {$sensitiveWord} ]
". "替换后为:[ {$stringAfter} ]"; } return $log; }
2. 调用方法
function testAction(){ // 要过滤的内容 $string = 'likeyou小白喜欢小黑爱着的大黄'; // 定义敏感词数组 $list = ['小明', '小红', '大白', '小白', '小黑', 'me', 'you']; $result = $this->sensitive($list, $string); echo ($result); die; # 打印结果: # 原句为 [ likeyou小白喜欢小黑爱着的大黄 ] # 匹配到 [ 3 ]个敏感词:[ you,小白,小黑 ] # 替换后为:[ like喜欢*爱着的大黄 ] }
两款非常方便的正则表达式工具:
JavaScript正则表达式在线测试工具
正则表达式在线生成工具
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/222479.html原文链接:https://javaforall.net
