DFAItem.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: stanley-king
  5. * Date: 16/5/8
  6. * Time: 下午1:50
  7. */
  8. namespace sensitive_word;
  9. class DFAItem
  10. {
  11. private $word = null;
  12. private $sub_items = array();
  13. private $is_end = 0;
  14. public function __set($name, $value)
  15. {
  16. $this->$name = $value;
  17. }
  18. public function __get($name)
  19. {
  20. return $this->$name;
  21. }
  22. // 初始化
  23. public function init($word)
  24. {
  25. $cnt = count($word);
  26. if ($cnt <= 0) {
  27. return null;
  28. } else if ($cnt === 1) {
  29. $this->is_end = 1;
  30. $this->word = $word[0];
  31. $this->sub_items = null;
  32. } else {
  33. $this->is_end = 0;
  34. $this->word = $word[0];
  35. $this->add_item(array_slice($word, 1));
  36. }
  37. return $this;
  38. }
  39. // 添加子节点内容
  40. public function add_item($word)
  41. {
  42. $subitem = new DFAItem();
  43. $ret = $subitem->init($word);
  44. if (!is_null($ret)) {
  45. array_push($this->sub_items, $subitem);
  46. }
  47. }
  48. // 向链表中添加内容
  49. public function addwords($word)
  50. {
  51. $found = false;
  52. foreach ($this->sub_items as $item) {
  53. if (0 == strcmp($word[0], $item->word)) {
  54. $item->addwords(array_slice($word, 1));
  55. $found = true;
  56. }
  57. }
  58. if (!$found) {
  59. $subitem = new DFAItem();
  60. $subitem->init($word);
  61. array_push($this->sub_items, $subitem);
  62. }
  63. }
  64. // 判断关键字是否在属于此item
  65. public function checkword($txt)
  66. {
  67. if (is_null($txt)) {
  68. return false;
  69. }
  70. $head = mb_substr($txt, 0, 1);
  71. $found = false;
  72. foreach ($this->sub_items as $item) {
  73. if (0 == strcmp($item->word, $head)) {
  74. if ($item->is_end == 1) {
  75. return true;
  76. } else {
  77. return $item->checkword(mb_substr($txt, 1));
  78. }
  79. }
  80. }
  81. if (!$found) {
  82. return false;
  83. }
  84. }
  85. }