<?php
namespace mobile\server;

class WordMatcher {

    public $dict = [];
    public $wordMaxLen = 0;

    function __construct(){
        if(! extension_loaded('mbstring')) {
            exit('extension mbstring is not loaded');
        }
    }

    function addWord($word) {
        $len = mb_strlen($word, 'utf-8');
        $this->wordMaxLen = $len > $this->wordMaxLen ? $len : $this->wordMaxLen;
        $this->dict[$word] = 1;
    }

    function removeWord($word) {
        unset($this->dict[$word]);
    }

    function match($str, &$matched) {
        if(mb_strlen($str) < 1) {
            return;
        }

        $len = $this->wordMaxLen;
        while($len>0) {
            $substr = mb_substr($str, 0, $len, 'utf-8');
            if(isset($this->dict[$substr])) {
                $matched[] = $substr;
                break;
            } else {
                $len--;
            }
        }
        if($len == 0) {
            $len = 1;
        }
        $str = mb_substr($str, $len,null, 'utf-8');
        $this->match($str, $matched);
    }

}