<?php namespace app\common\library; use think\Hook; use think\Config; /** * 关键词检索类 */ class Keyworld { /** * @todo 敏感词过滤,返回结果 * @param array $list 定义敏感词一维数组 * @param string $string 要过滤的内容 * @return string $log 处理结果 */ public static function sensitive_old($string){ $count = 0; //违规词的个数 $sensitiveWord = ''; //违规词 $stringAfter = $string; //替换后的内容 $list = config('keyworld'); //定义敏感词数组 $pattern = "/".implode("|",$list)."/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),'*')); //把匹配到的数组进行合并,替换使用 $replace_arr = [1=>'*',2=>'**',3=>'***',4=>'****',5=>'*****','more'=>'*****...',]; $replaceArray = []; foreach($patternList as $key => $val){ $replaceArray[$val] = isset($replace_arr[mb_strlen($val)]) ? $replace_arr[mb_strlen($val)] : $replace_arr['more']; } $stringAfter = strtr($string, $replaceArray); //结果替换 } /*$rs = []; $rs['string'] = $string; $rs['count'] = $count; $rs['keyworld'] = $patternList; $rs['newstring'] = $stringAfter;*/ return $stringAfter; } public static function sensitive($string){ if(empty($string)){ return $string; } $list = config('keyworld'); //定义敏感词数组 $replaceArray = []; //含有的违禁词集合 foreach($list as $key => $word){ if(empty($word)){ continue; } $start = strpos($string,$word); if($start !== false){ $replaceArray[$word] = '*'; } } $stringAfter = strtr($string, $replaceArray); //结果替换 return $stringAfter; } public static function checkAction($data,$fields){ //$string = 'likeyou小白喜欢小黑爱着的大黄'; //要过滤的内容 foreach($data as $key => $string){ if(in_array($key,$fields)){ $data[$key] = self::sensitive($string); } } return $data; } }