WordMatcher.php 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. namespace mobile\server;
  3. class WordMatcher {
  4. public $dict = [];
  5. public $wordMaxLen = 0;
  6. function __construct(){
  7. if(! extension_loaded('mbstring')) {
  8. exit('extension mbstring is not loaded');
  9. }
  10. }
  11. function addWord($word) {
  12. $len = mb_strlen($word, 'utf-8');
  13. $this->wordMaxLen = $len > $this->wordMaxLen ? $len : $this->wordMaxLen;
  14. $this->dict[$word] = 1;
  15. }
  16. function removeWord($word) {
  17. unset($this->dict[$word]);
  18. }
  19. function match($str, &$matched) {
  20. if(mb_strlen($str) < 1) {
  21. return;
  22. }
  23. $len = $this->wordMaxLen;
  24. while($len>0) {
  25. $substr = mb_substr($str, 0, $len, 'utf-8');
  26. if(isset($this->dict[$substr])) {
  27. $matched[] = $substr;
  28. break;
  29. } else {
  30. $len--;
  31. }
  32. }
  33. if($len == 0) {
  34. $len = 1;
  35. }
  36. $str = mb_substr($str, $len,null, 'utf-8');
  37. $this->match($str, $matched);
  38. }
  39. }