实现方法1 使用PHP扩展trie_filter
安装:libiconv
wget http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.14.tar.gz
tar zxvf libiconv-1.14.tar.gz
cd libiconv-1.14
./configure
make
make install
phpinfo() 查看是否安装
安装:libdatrie
下载地址:https://linux.thai.net/~thep/datrie/datrie.html#Download 版本0.2.4
phpize
./configure --with-php-config=/usr/local/php/bin/php-config --with-trie_filter=/usr/local/lib
make
make install
网上大部分的下载包对PHP7支持有问题,从网上找了一份支持7的下载包
wget https://github.com/jiopuud/trie_filter/archive/master.zip
phpize
./configure --with-php-config=/usr/local/php/bin/php-config --with-trie_filter=/usr/local/lib
make clean
make
make install
更新php.ini文件
增加:extension=trie_filter.so
保存并重新启动php-fpm服务。
phpinfo() 查看服务安装
/*代码实现敏感词过滤*/ //生成敏感词字典 $str = "老王,你就是个混蛋,打电话不接,发微信不回,你要是再不回信,你就是成了老混蛋了"; Filter($str); public function createDict() { $resTrie = trie_filter_new(); $words = array('混蛋','回信','发微信'); foreach ($words as $k => $v) { trie_filter_store($resTrie, $v); } trie_filter_save($resTrie,'/PATH/dict.tree'); } public function Filter($str) { $resTrie = trie_filter_new(); //加载字典 $dict = trie_filter_load('/PATH/dict.tree'); $res = trie_filter_search_all($dict, $str); var_dump($res); }
问题点总结:1 安装libdatrie服务时,使用最新版本会报错,最全决定使0.2.4版本
2 git上trie_filter拓展包对当前php7不支持,安装是会报错,所以从网上查找一份支持php7的包。