Keyworld.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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_old($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 sensitive($string){
  42. if(empty($string)){
  43. return $string;
  44. }
  45. $list = config('keyworld'); //定义敏感词数组
  46. $replaceArray = []; //含有的违禁词集合
  47. foreach($list as $key => $word){
  48. if(empty($word)){
  49. continue;
  50. }
  51. $start = strpos($string,$word);
  52. if($start !== false){
  53. $replaceArray[$word] = '*';
  54. }
  55. }
  56. $stringAfter = strtr($string, $replaceArray); //结果替换
  57. return $stringAfter;
  58. }
  59. public static function checkAction($data,$fields){
  60. //$string = 'likeyou小白喜欢小黑爱着的大黄'; //要过滤的内容
  61. foreach($data as $key => $string){
  62. if(in_array($key,$fields)){
  63. $data[$key] = self::sensitive($string);
  64. }
  65. }
  66. return $data;
  67. }
  68. }