php 敏感词 过滤 方法

博客提到从数据库查询敏感词进行替换并非好方式,大牛们通常将需替换的敏感词保存到文件或缓存中,并将介绍保存文件的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 /**
 *  敏感词 
 */
function senswords($content){
	$words  = M('senswords')->where('status=0')->field('words')->select();
	$badword = array_column($words, 'words');
	$badword1 = array_combine($badword,array_fill(0,count($badword),'*'));
    $str = strtr($content, $badword1);
	return $str;
}

敏感词 过滤 从数据库 中查询 出 需要替换的 词  还是比较简单 而且不是很好的方式  作为小白的 小编  发现大牛们一般都是

保存到 一个文件里 或者 缓存中  

保存文件方法 :

class SenswordsService
{
    protected  $words_file_path = "./senswords.txt";

    //修改关键词 过滤
    public function get_words($content){
        //是否为空
        if(empty($content)){
            return $content;
        }
        //是否为 字符串
        if(!is_string($content)){
            strtr($content);
        }
        $file_path = $this->words_file_path;
        $words = '';
        if(file_exists($file_path)) {
            $words = file_get_contents($file_path);//将整个文件内容读入到一个字符串中
        }
        if($words){
            $badword = explode(',',$words);
            $badword1 = array_combine($badword,array_fill(0,count($badword),str_repeat('*',3)));
            $str = strtr($content,$badword1);
            return $str;
        }
        return $content;
    }

    //修改关键词
    public function edit_words($words=''){
        $file_path = $this->words_file_path;
        $words_arr = Db('senswords')->where(['status'=>1])->column('words');
        $words_str =  implode(',',$words_arr);
        $words = '';
        if(file_exists($file_path)) {
            $words = file_get_contents($file_path);//将整个文件内容读入到一个字符串中
        }
        if($words){
            //追加
            return file_put_contents($file_path,$words_str,FILE_APPEND);
        }else{
            return file_put_contents($file_path,$words_str);
        }
    }


}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值