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

yipeiwu_com7年前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中is_file不能替代file_exists的理由

我们可以使用下面的代码测试一下:复制代码 代码如下:<?php        $filename = 'test.txt...

php使用Jpgraph绘制饼状图的方法

php使用Jpgraph绘制饼状图的方法

本文实例讲述了php使用Jpgraph绘制饼状图的方法。分享给大家供大家参考。具体实现方法如下: <?php include ("src/jpgraph.php");...

Eclipse中php插件安装及Xdebug配置的使用详解

Eclipse中php插件安装及Xdebug配置的使用详解

由于在android开发团队,又迷上了android自动化测试,所有一直使用Eclipse做为开发工具。以前使用Zend Studio 9.0.1做为PHP的开发工具,现在放弃使用Zen...

php中cookie实现二级域名可访问操作的方法

本文实例讲述了php中cookie实现二级域名可访问操作的方法。分享给大家供大家参考。具体方法如下: cookie在一些应用中很常用,假设我有一个多级域名要求可以同时访问主域名绑定的co...

php使用PDO执行SQL语句的方法分析

本文实例讲述了php使用PDO执行SQL语句的方法。分享给大家供大家参考,具体如下: exec()方法 exec()方法返回执行后受影响行数,语法如下: int PDO::exec(st...