'*',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; } }