Words.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace ins;
  3. class words
  4. {
  5. private $words;
  6. private $replaceChar;
  7. private $fuzzyMatch;
  8. private $txtDir = IA_ROOT_WK.'/extend/ins/text';
  9. public function __construct($replaceChar = '*', $fuzzyMatch = false)
  10. {
  11. $this->replaceChar = $replaceChar;
  12. $this->fuzzyMatch = $fuzzyMatch;
  13. $this->setWords($this->txtDir);
  14. }
  15. public function setWords($dir)
  16. {
  17. $txtArr = $this->readTxtFiles($dir);
  18. $wordArr = explode(',', implode(',', $txtArr));
  19. foreach ($wordArr as $k => $v) {
  20. if (empty(trim($v))) {
  21. unset($wordArr[$k]);
  22. }
  23. }
  24. $this->words = array_chunk($wordArr, 100);
  25. }
  26. public function getWords()
  27. {
  28. $dir = $this->txtDir;
  29. $txtArr = $this->readTxtFiles($dir);
  30. $wordArr = explode(',', implode(',', $txtArr));
  31. // foreach ($wordArr as $k => $v) {
  32. // if (empty(trim($v))) {
  33. // unset($wordArr[$k]);
  34. // }
  35. // }
  36. $text = implode(',', $wordArr);
  37. return $text;
  38. }
  39. /**
  40. * @param $folderPath
  41. * @return array
  42. * 遍历读取文件夹下txt内容
  43. */
  44. private function readTxtFiles($folderPath)
  45. {
  46. $arr = [];
  47. if (is_dir($folderPath)) {
  48. $files = scandir($folderPath);
  49. foreach ($files as $file) {
  50. $filePath = $folderPath . '/' . $file;
  51. if (is_file($filePath) && pathinfo($filePath, PATHINFO_EXTENSION) === 'php') {
  52. $content = file_get_contents($filePath);
  53. $content = str_replace(['<?php', '/*', '*/'], '', $content);
  54. $content = trim($content);
  55. $arr[$file] = $content;
  56. }
  57. }
  58. }
  59. return $arr;
  60. }
  61. public function filter($text)
  62. {
  63. $result = $text;
  64. foreach($this->words as $arr) {
  65. foreach($arr as $word) {
  66. $star = str_repeat('*', mb_strlen($word, 'utf-8'));
  67. $result = str_replace($word, $star, $result);
  68. }
  69. }
  70. return $result;
  71. }
  72. }