欢迎来到代码驿站!

PHP代码

当前位置:首页 > 软件编程 > PHP代码

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

时间:2021-02-25 10:40:01|栏目: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代码

下一篇:php session和cookie使用说明

本文标题:PHP实现的敏感词过滤方法示例

本文地址:http://www.codeinn.net/misctech/69908.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有