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

yipeiwu_com6年前PHP代码库

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

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} ]<br/>";
  if($count==0){
    $log .= "暂未匹配到敏感词!";
  }else{
    $log .= "匹配到 [ {$count} ]个敏感词:[ {$sensitiveWord} ]<br/>".
      "替换后为:[ {$stringAfter} ]";
  }
  return $log;
}

2、调用方法

function testAction(){
  $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程序设计有所帮助。

相关文章

php header 详细使用说明与使用心得第1/2页

不管页面有多少header,它会执行最后一个,不过是有条件的,例如: header('Location://www.jb51.net'); header('Location:http:/...

php-fpm超时时间设置request_terminate_timeout资源问题分析

php-fpm超时时间设置request_terminate_timeout资源问题分析

php日志中有一条超时的日志,但是我request_terminate_timeout中设置的是0,理论上应该没有超时时间才对。 PHP Fatal error: Maximum exe...

PHP调用MsSQL Server 2012存储过程获取多结果集(包含output参数)的详解

【PHP Source Code】:复制代码 代码如下:$dbh = new PDO('sqlsrv:server=连接地址;Database=数据库名', 用户名, 密码);try {...

PHP 过滤页面中的BOM(实现代码)

复制代码 代码如下:function checkBOM ($filename) {       $contents = fil...

PHP版 汉字转码的实现详解

如下所示:复制代码 代码如下:<?phpfunction unicode_encode($str, $encoding='GBK', $prefix='&#', $postfix=...