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


 $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);
    }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM