> For the complete documentation index, see [llms.txt](https://bing.gitbook.io/phper/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://bing.gitbook.io/phper/php/6.-chang-jian-wen-ti/min-gan-ci-guo-lv.md).

# 敏感词过滤

使用php扩展trie\_filter，利用词库，过滤敏感词

### 功能

关键词过滤扩展，用于检查一段文本中是否出现敏感词，基于Double-Array Trie 树实现。

安装步骤 下面的$LIB\_PATH为依赖库安装目录，$INSTALL\_PHP\_PATH为PHP5安装目录。

### 安装libdatrie依赖库

下载地址：<http://linux.thai.net/\\~thep/datrie/datrie.html#Download> $ tar zxvf libdatrie-0.2.4.tar.gz $ cd libdatrie-0.2.4 $ make clean $ ./configure --prefix=$LIB\_PATH $ make $ makeinstall

### 安装trie\_filter扩展 （<https://github.com/wulijun/php-ext-trie-filter）>

$ $INSTALL\_PHP\_PATH/bin/phpize $ ./configure --with-php-config=$INSTALL\_PHP\_PATH/bin/php-config --with-trie\_filter=$LIB\_PATH $ make $ makeinstall 然后修改php.ini，增加一行：extension=trie\_filter.so，然后重启PHP。

### PHP测试实例

```
<?php
ini_set('memory_limit', '512M');
$arrWord = file('dict.txt');
$resTrie = trie_filter_new();
foreach ($arrWord as $k => $v) {
    trie_filter_store($resTrie, $v);
}
trie_filter_save($resTrie, __DIR__ . '/blackword.tree');
$resTrie = trie_filter_load(__DIR__ . '/blackword.tree');
$str = '合作证书办一个诚字，做事一个信字。 给我们一次机会，也给自己一份希望。炒股靠消息，提供内部股，内部信息现在散户的消息来源99%以上
来源于电视，报纸，网络但是其中有多少是托，你又怎么知道呢，放出的一些假消息让股民赢小利，亏大钱你还处于这种运做模式吗？可能你现在在想是
真是假，如果心动的话，可以jia我，我会给你一个答案！═☆ 稳中求胜 ══★QQ<<8 ..2 0>>7 9 9 <<1 3  ..2>>';
$arrRet = trie_filter_search_all($resTrie, $str);
print_all($str, $arrRet);
function print_all($str, $res) {//print_r($res);
    echo "$str\n";
    foreach ($res as $k => $v) {
        echo $k."=>{$v[0]}-{$v[1]}-".substr($str, $v[0], $v[1])."\n";
    }
}
```

测试效果，输出格式（顺序值=>该敏感词出现的位置-该敏感词的长度-敏感词）

### 注意事项

dict.txt 为敏感词库，一个词一行 PHP需要5.2以上版本
