PHP 敏感词替换 *

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

    function testAction(){
    
    
        $string = '操,你这个傻逼'; //要过滤的内容
        $list = ['操', '傻逼', '你妈的', '他妈的', 'fuck'];  //定义敏感词数组
        $result = $this->sensitive($list, $string);
        echo $result;
        //打印结果:
        /*
        原句为 [ 操,你这个傻逼 ]
        匹配到 [ 2 ]个敏感词:[ 操,傻逼 ]
        替换后为:[ *,你这个* ]
          */
    }


转载自: https://my.oschina.net/u/3857688/blog/3024625

猜你喜欢

转载自blog.csdn.net/qq_39004843/article/details/111943193