PHP实现的敏感词过滤方法示例
本文实例讲述了PHP实现的敏感词过滤方法。分享给大家供大家参考,具体如下:
1、敏感词过滤方法
/**
*@todo敏感词过滤,返回结果
*@paramarray$list定义敏感词一维数组
*@paramstring$string要过滤的内容
*@returnstring$log处理结果
*/
functionsensitive($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、调用方法
functiontestAction(){
$string='likeyou小白喜欢小黑爱着的大黄';//要过滤的内容
$list=['小明','小红','大白','小白','小黑','me','you'];//定义敏感词数组
$result=$this->sensitive($list,$string);
echo($result);
die;
//打印结果:
/*
原句为[likeyou小白喜欢小黑爱着的大黄]
匹配到[3]个敏感词:[you,小白,小黑]
替换后为:[like**喜欢*爱着的大黄]
*/
}
PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:
JavaScript正则表达式在线测试工具:
http://tools.jb51.net/regex/javascript
正则表达式在线生成工具:
http://tools.jb51.net/regex/create_reg
更多关于PHP相关内容感兴趣的读者可查看本站专题:《php正则表达式用法总结》、《php程序设计安全教程》、《php安全过滤技巧总结》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《php字符串(string)用法总结》及《php+mysql数据库操作入门教程》
希望本文所述对大家PHP程序设计有所帮助。