zoukankan      html  css  js  c++  java
  • PHP实现的敏感词过滤方法

    PHP实现的敏感词过滤方法,以下是一份过滤敏感词的编码。有需要可以参考参考。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    /**
     * @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;
    }

      调用方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    function testAction(){
     $string 'likeyou小白喜欢小黑爱着的大黄'//要过滤的内容
     $list = ['小明''小红''大白''小白''小黑''me''you']; //定义敏感词数组
     $result $this->sensitive($list$string);
     echo ($result);
     die;
     //打印结果:
     /*
     原句为 [ likeyou小白喜欢小黑爱着的大黄 ]
     匹配到 [ 3 ]个敏感词:[ you,小白,小黑 ]
     替换后为:[ like**喜欢*爱着的大黄 ]
     */
    }
  • 相关阅读:
    【转】5亿个数找中位数
    C++二维数组名的再探索
    转载 图像卷积
    PowerDesigner的使用一
    Spring注解详解
    JSP页面以及简单的指令
    Javascript学习总结
    html第一天
    Chrome开发,debug的使用方法。
    SVN使用
  • 原文地址:https://www.cnblogs.com/xu1115/p/15237002.html
Copyright © 2011-2022 走看看