1.在TP框架对应模块下面创建 WordsFilterBehavior 类、
位置Application/Home/Behavior/下
<?php namespace HomeBehavior; use ThinkBehavior; use ThinkLog; class WordsFilterBehavior extends Behavior { public function run(&$params) { $this->loopFilter($params); } /** * 实现无限极替换 * @param $params * @Author: lihuan * @Date: 2020-3-16 14:57 */ private function loopFilter(&$params) { if(is_string($params)){ $params = $this->filter($params); }else if(is_array($params)){ foreach ($params as $key=>$val){ if(is_string($val)){ $params[$key] = $this->filter($val); }else{ $this->loopFilter($params[$key]); } } } } private function filter($string) { $words = $this->words(); //$count = 0; //违规词的个数 //$sensitiveWord = ''; //违规词 $stringAfter = $string; //替换后的内容 $pattern = "/".implode("|",$words)."/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 = " ".date('Y-m-d H:i:s')." 原句为 [ {$string} ]<br/>"; // if($count==0){ // $log .= "暂未匹配到敏感词!"; // }else{ // $log .= "匹配到 [ {$count} ]个敏感词:[ {$sensitiveWord} ]<br/>". // "替换后为:[ {$stringAfter} ]"; // } // Log::write($log,self::ERR,'',C('LOG_PATH').date('y_m_d').'_replacewords.log'); return $stringAfter; } /** * 敏感词词组 * @return array * @Author: lihuan * @Date: 2020-3-16 14:40 */ private function words() { return [ '枪支', '弹药', '枪' ]; } }
2.在tags.php配置文件内注册
位置在Application/Config/下
return array( // 表单提交过滤敏感词 'form_submit' => array('HomeBehaviorWordsFilterBehavior') );
3.在代码库内需要的位置引用
#在文件头引入钩子类 use ThinkHook; #调用 $data需要操作的数据,字符串或者数组 Hook::listen('form_submit',$data);//这是一个敏感词过滤的测试