php扩展trie_filter 过滤关键词

 

https://blog.csdn.net/json_ligege/article/details/73250315

 

php扩展trie_filter 过滤关键词

在项目中需要对用户传递过来的文字进行过滤敏感词,用到这个,今天有时间研究了一下,故写了这篇博客。
关键词过滤扩展,用于检查一段文本中是否出现敏感词,基于Double-Array Trie 树实现
安装 libdatrie , 需要 libdatrie-0.2.4 或更新的版本
它依赖 libiconv .
安装:
  1.  
    wget http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.14.tar.gz
  2.  
    tar -zxf libiconv-1.14.tar.gz
  3.  
    cd libiconv-1.14
  4.  
    ./configure
  5.  
    make && make install
libdatrie 下载地址:
http://download.csdn.net/download/json_ligege/9870583
安装:
  1.  
    wget ftp://linux.thai.net/pub/ThaiLinux/software/libthai/libdatrie-0.2.4.tar.gz
  2.  
    tar -zxf libdatrie-0.2.4.tar.gz
  3.  
    cd libdatrie-0.2.4
  4.  
     
  5.  
    ./configure --prefix=/usr/local/libdatrie/
  6.  
    make ICONV_LIBS='/usr/local/lib/libiconv.so'
  7.  
    make install
安装 PHP 扩展
  1.  
    wget https://github.com/wulijun/php-ext-trie-filter/archive/master.zip
  2.  
    unzip master.zip
  3.  
    cd php-ext-trie-filter-master/
  4.  
    phpize
  5.  
    ./configure --with-php-config=/usr/local/php/bin/php-config --with-trie_filter=/usr/local/libdatrie/
  6.  
    make && make install
  7.  
     
将生成的 trie_filter.so 文件复制到 php 扩展目录,并在 php.ini 中添加该文件
安装完后,在 phpinfo 里可以看到 trie_filter 扩展
如图:

这样就安装成功了。
使用示例:
  1.  
    $arrWord = array('word1', 'word2', 'word3');
  2.  
    $resTrie = trie_filter_new(); //create an empty trie tree
  3.  
    foreach ($arrWord as $k => $v) {
  4.  
    trie_filter_store($resTrie, $v);
  5.  
    }
  6.  
    // 生成关键词词典.
  7.  
    trie_filter_save($resTrie, __DIR__ . '/blackword.tree');
  8.  
     
  9.  
    // 加载关键词词典,成功返回一个Trie_Filter 资源句柄,失败返回NULL
  10.  
    $resTrie = trie_filter_load(__DIR__ . '/blackword.tree');
  11.  
     
  12.  
    $strContent = 'hello word2 word1';
  13.  
    // 查找关键词
  14.  
    $arrRet = trie_filter_search($resTrie, $strContent);//每次只检测一个敏感词
  15.  
    print_r($arrRet); //Array(0 => 6, 1 => 5)
  16.  
     
  17.  
    echo substr($strContent, $arrRet[0], $arrRet[1]); //word2
  18.  
     
  19.  
    $arrRet = trie_filter_search_all($resTrie, $strContent);//一次把所有的敏感词都检测出来
  20.  
    print_r($arrRet); //Array(0 => Array(0 => 6, 1 => 5), 1 => Array(0 => 12, 1 => 5))
  21.  
     
  22.  
    $arrRet = trie_filter_search($resTrie, 'hello word');
  23.  
    print_r($arrRet); //Array()
  24.  
     
  25.  
    // 获得查找结果树
  26.  
    trie_filter_free($resTrie);

建议使用php5.3.3以上的版本,我使用的是5.3.3

 

使用5.2.17版本时候:trie_filter_search_all 这个函数可能会有错误

 

 

 

 

 

posted @ 2018-09-02 12:49  西伯利亚狼520  阅读(734)  评论(0)    收藏  举报