SensitiveWordInit.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. /**
  3. * 初始化敏感词库<br>
  4. * 将敏感词加入到HashMap中<br>
  5. * 构建DFA算法模型
  6. *
  7. * @author dxm
  8. *
  9. */
  10. namespace sensitive_word;
  11. require_once(BASE_ROOT_PATH . "/helper/sensitive/DFAItem.php");
  12. class SensitiveWordInit
  13. {
  14. // 字符编码
  15. const ENCODING = "UTF-8";
  16. /**
  17. * 初始化敏感字库
  18. *
  19. * @return
  20. */
  21. public function initKeyWord()
  22. {
  23. $word_array = $this->readSensitiveWordFile();
  24. return $this->addSensitiveWordToHashMap($word_array);
  25. }
  26. /**
  27. * 读取敏感词库,将敏感词放入HashSet中,构建一个DFA算法模型:<br>
  28. * 中 = { isEnd = 0 国 = {<br>
  29. * isEnd = 1 人 = {isEnd = 0 民 = {isEnd = 1} } 男 = { isEnd = 0 人 = { isEnd =
  30. * 1 } } } } 五 = { isEnd = 0 星 = { isEnd = 0 红 = { isEnd = 0 旗 = { isEnd = 1
  31. * } } } }
  32. *
  33. */
  34. public function addSensitiveWordToHashMap($words)
  35. {
  36. $dfa = new DFAItem();
  37. foreach ($words as $word) {
  38. $dfa->addwords(explode(" ",$word));
  39. }
  40. return $dfa;
  41. }
  42. /**
  43. * 读取敏感词库中的内容,将内容添加到array中
  44. *
  45. * @return
  46. * @throws Exception
  47. */
  48. private function readSensitiveWordFile()
  49. {
  50. $word_array = array();
  51. array_push($word_array, '中 国');
  52. array_push($word_array, '中 央');
  53. array_push($word_array, '国 家');
  54. array_push($word_array, '他 妈 的');
  55. return $word_array;
  56. }
  57. }