PHP生成Trie树

将所有敏感词生成 Trie 树结构,便于做敏感词检测,生成代码如下

10年积累的网站设计、网站建设经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站制作后付款的网站建设流程,更有庆城免费网站建设让你可以放心的选择与我们合作。

class TrieNode
{

    private static $TrieTree;

    public function __construct()
    {
        static::$TrieTree = [];
    }

    public function insert($sensWords): TrieNode
    {
        $words = preg_split('//u', $sensWords, -1, PREG_SPLIT_NO_EMPTY);
        $_tree =  &static::$TrieTree;
        foreach ($words as $key => $_word) {
            if (!isset($_tree[$_word])) {
                $_tree[$_word] = [
                    'isEnd' => !isset($words[$key + 1]),
                    'child' => []
                ];
            }
            $_tree = &$_tree[$_word]['child'];
        }
        return $this;
    }

    public function getTree()
    {
        return static::$TrieTree;
    }
}

$treeNode = (new TrieNode)->insert('CNM')->insert('MLGB')->insert('WRNM')->getTree();
echo json_encode($treeNode,JSON_UNESCAPED_UNICODE);

当前文章:PHP生成Trie树
当前网址:http://scyanting.com/article/psdosg.html