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变量范围介绍

例如: 复制代码 代码如下: <?php $a = 1; include 'b.inc'; ?> 这里变量 $a 将会在包含文件 b.inc 中生效。但是,在用户自定义函数...

getimagesize获取图片尺寸实例

本文实例讲述了getimagesize获取图片尺寸的方法。分享给大家供大家参考。具体如下: php有现成的函数getimagesize用于获取图像的尺寸,代码示例: 复制代码 代码如下:...

深入apache host的配置详解

<VirtualHost *:80>    ServerAdmin webmaster@dummy-host.127.0.0.1 &n...

php实现点击可刷新验证码

本文实例为大家分享了php点击可刷新验证码的具体代码,供大家参考,具体内容如下 验证码类文件 CreateImg.class.php <?php class Va...

解析php中的fopen()函数用打开文件模式说明

fopen() 函数用于在 PHP 中打开文件。此函数的第一个参数含有要打开的文件的名称,第二个参数规定了使用哪种模式来打开文件:复制代码 代码如下:<?php$file=fope...