/**
* 敏感词
*/
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);
}
}
}