一个高效过滤敏感词的方法

 $badword = [   
        '张三',
        '张三丰',
        '张三丰田'   
    ];    

    $str = '我今天开着张三丰田上班';    
    echo replaceBadWords($badword,$str);
    
    /**
     * 过滤敏感词(将敏感词替换成"*"号)
     * @param array $bad_words_arr [敏感词数组]
     * @param string $replace_str [要处理的字符串]
     **/
    function replaceBadWords($bad_words_arr,$replace_str){

        if(!is_array($bad_words_arr) || empty($bad_words_arr)){
            return $replace_str;
        }

        $null_arr=array_fill(0, count($bad_words_arr), '*'); //生成一个只有"*"元素的数组
        
        $replace_arr=array_combine($bad_words_arr,$null_arr); //合并数组

        return strtr($replace_str,$replace_arr);
    }

 

posted @ 2017-04-20 16:44  doforme  阅读(3013)  评论(0编辑  收藏  举报