Keyworld.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace app\common\library;
  3. use think\Hook;
  4. use think\Config;
  5. /**
  6. * 关键词检索类
  7. */
  8. class Keyworld
  9. {
  10. /**
  11. * @todo 敏感词过滤,返回结果
  12. * @param array $list 定义敏感词一维数组
  13. * @param string $string 要过滤的内容
  14. * @return string $log 处理结果
  15. */
  16. public static function sensitive($string){
  17. $count = 0; //违规词的个数
  18. $sensitiveWord = ''; //违规词
  19. $stringAfter = $string; //替换后的内容
  20. $list = config('keyworld'); //定义敏感词数组
  21. $pattern = "/".implode("|",$list)."/i"; //定义正则表达式
  22. if(preg_match_all($pattern, $string, $matches)){ //匹配到了结果
  23. $patternList = $matches[0]; //匹配到的数组
  24. $count = count($patternList);
  25. //$sensitiveWord = implode(',', $patternList); //敏感词数组转字符串
  26. //$replaceArray = array_combine($patternList,array_fill(0,count($patternList),'*')); //把匹配到的数组进行合并,替换使用
  27. $replace_arr = [1=>'*',2=>'**',3=>'***',4=>'****',5=>'*****','more'=>'*****...',];
  28. $replaceArray = [];
  29. foreach($patternList as $key => $val){
  30. $replaceArray[$val] = isset($replace_arr[mb_strlen($val)]) ? $replace_arr[mb_strlen($val)] : $replace_arr['more'];
  31. }
  32. $stringAfter = strtr($string, $replaceArray); //结果替换
  33. }
  34. /*$rs = [];
  35. $rs['string'] = $string;
  36. $rs['count'] = $count;
  37. $rs['keyworld'] = $patternList;
  38. $rs['newstring'] = $stringAfter;*/
  39. return $stringAfter;
  40. }
  41. public static function checkAction($data,$fields){
  42. //$string = 'likeyou小白喜欢小黑爱着的大黄'; //要过滤的内容
  43. foreach($data as $key => $string){
  44. if(in_array($key,$fields)){
  45. $data[$key] = self::sensitive($string);
  46. }
  47. }
  48. return $data;
  49. }
  50. }