日期:2014-05-16  浏览次数:20453 次

敏感词汇过滤
假如用户输入了 
$str="输入内容123";

下了个abc.txt,内容为,大概一千条
坏蛋|1
火枪|1
超级大坏蛋|1
....


如何用这个txt文件检查过滤$str1;要效率,求支招

------解决方案--------------------
以 http://bbs.csdn.net/topics/390221822 的 ttrie 类为例
trie = new TTrie;
foreach(file('abc.txt') as $r) $trie->set(strtok($r, '
------解决方案--------------------
'));
$s =<<< TXT
输入内容坏蛋123
TXT;
//仅识别
print_r($trie->match($s));
/* 得
Array
(
    [0] => 输入内容
    [1] => 坏蛋
    [2] => 123
)
*/

//去掉字典字
$trie->savematch = 0;
print_r($trie->match($s));
/* 得
Array
(
    [0] => 输入内容
    [1] => 123
)
*/

显然已经满足你的需要了
输出结果时连接数组为串就可以了

如果是想加亮关键字,可以这样
class mytrie extends ttrie {
  function b() {
    $this->buffer[] = '<b>' . array_pop($this->buffer) . '<b/>';
  }
}
    
$trie = new mytrie;
foreach(file('abc.txt') as $r) $trie->set(strtok($r, '
------解决方案--------------------
'), 'b');
$s =<<< TXT
输入内容坏蛋123
TXT;
print_r($trie->match($s));
/* 得
Array
(
    [0] => 输入内容
    [1] => <b>坏蛋<b/> 《== 这个就被突出显示了
    [2] => 123
)
*/

其实渔已经给你了,鱼还是自己动手的好

为了使实例化的对象得以复用,还应在 match 方法开始处加入
    $this->buffer = array();
    $this->input = 0;
    $this->backtracking = 0;
以重新初始化数据指针