当前位置:首页 > PHP教程 > php应用 > 列表

PHP实现的敏感词过滤方法示例

发布:smiling 来源: PHP粉丝网  添加日期:2021-11-11 16:58:45 浏览: 评论:0 

这篇文章主要介绍了PHP实现的敏感词过滤方法,涉及php字符串正则匹配、分割、转换等相关操作技巧,需要的朋友可以参考下。

本文实例讲述了PHP实现的敏感词过滤方法,分享给大家供大家参考,具体如下:

1、敏感词过滤方法

  1. /** 
  2.  * @todo 敏感词过滤,返回结果 
  3.  * @param array $list  定义敏感词一维数组 
  4.  * @param string $string 要过滤的内容 
  5.  * @return string $log 处理结果 
  6.  */ 
  7. function sensitive($list, $string){ 
  8.   $count = 0; //违规词的个数 
  9.   $sensitiveWord = '';  //违规词 
  10.   $stringAfter = $string;  //替换后的内容 
  11.   $pattern = "/".implode("|",$list)."/i"; //定义正则表达式 
  12.   if(preg_match_all($pattern, $string, $matches)){ //匹配到了结果 
  13.     $patternList = $matches[0];  //匹配到的数组 
  14.     $count = count($patternList); 
  15.     $sensitiveWord = implode(',', $patternList); //敏感词数组转字符串 
  16.     $replaceArray = array_combine($patternList,array_fill(0,count($patternList),'*')); //把匹配到的数组进行合并,替换使用 
  17.     $stringAfter = strtr($string, $replaceArray); //结果替换 
  18.   } 
  19.   $log = "原句为 [ {$string} ]<br/>"; 
  20.   if($count==0){ 
  21.     $log .= "暂未匹配到敏感词!"; 
  22.   }else{ 
  23.     $log .= "匹配到 [ {$count} ]个敏感词:[ {$sensitiveWord} ]<br/>". 
  24.       "替换后为:[ {$stringAfter} ]"; 
  25.   } 
  26.   return $log; 
  27. } 

2、调用方法

  1. function testAction(){ 
  2.   $string = 'likeyou小白喜欢小黑爱着的大黄'; //要过滤的内容 
  3.   $list = ['小明', '小红', '大白', '小白', '小黑', 'me', 'you'];  //定义敏感词数组 
  4.   $result = $this->sensitive($list, $string); 
  5.   echo ($result); 
  6.   die; 
  7.   //打印结果: 
  8.   /* 
  9.   原句为 [ likeyou小白喜欢小黑爱着的大黄 ] 
  10.   匹配到 [ 3 ]个敏感词:[ you,小白,小黑 ] 
  11.   替换后为:[ like**喜欢*爱着的大黄 ] 
  12.     */ 
  13. }

Tags: PHP敏感词过滤

分享到: