PS:原创文章,如需转载,请注明出处,谢谢!      
本文地址:http://flyer0126.iteye.com/blog/1931212 
  
      早就想研究下敏感词过滤问题,今天有些时间,正好实践一下。 
  1. 安装:libdatrie (http://linux.thai.net/~thep/datrie/datrie.html#Download) 
 
 tar zxf libdatrie-0.2.4.tar.gz  
cd libdatrie-0.2.4  
./configure --prefix=/usr/local  
make  
make install 
  2. 安装 trie_filter 扩展 (https://code.google.com/p/as3chat/downloads/detail?name=trie_filter-2011-03-21.tar.gz) 
 
 tar zxf trie_filter-2011.03.21.tar.gz  
cd trie_filter-2011.03.21  
phpize (#/usr/local/php/bin/phpize )  
./configure --with-php-config=/usr/local/php/bin/php-config  
make  
make install  
  3. 修改 php.ini 文件,添加 trie_filter 扩展:extension=trie_filter.so,重启PHP。 
  查看phpinfo发现trie_filter 扩展可用,如下图所示: 
 
 4. 生成敏感词词典 (dpp 在 trie_filter-1.0.0 里面)   
  将需要检测的敏感词写入一文本文件(如:mgc.txt),每行一个敏感词,然后使用dpp处理文本文件生成词典。 
  规则:./dpp txt_file_path dict_file_path  
  示例:./dpp ~/mgc.txt mgc.dic  
  5. 应用 
 
<?php 
/** 
* trie_filter 敏感词过滤示例 
*  
* @author flyer0126 
* @since  2013/08/26 
**/ 
// 载入词典,成功返回一个 Trie_Filter 资源句柄,失败返回 NULL 
$file = trie_filter_load('/usr/local/src/trie_filter/mgc.dic'); 
var_dump($file); 
$str1 = '今天利用trie_filter做敏感词过滤示例'; 
$str2 = '今天利用trie_filter做过滤示例'; 
// 检测文本中是否含有词典中定义的敏感词(假设敏感词设定为:‘敏感词’) 
$res1 = trie_filter_search($file, $str1); 
$res2 = trie_filter_search($file, $str2); 
echo $res1 ? '存在敏感词' : '不存在敏感词'; 
echo "<br/>"; 
echo $res2 ? '存在敏感词' : '不存在敏感词'; 
/** 
resource(1) of type (Trie tree filter) 
存在敏感词 
不存在敏感词 
**/ 
  
  
    对应 libdatrie-0.2.4.tar.gz 及 trie_filter-2011-03-21.tar.gz 已添加至附件中,有兴趣的可以拿走~ 
       |