日期:2014-05-17 浏览次数:20759 次
include 'TTrie.php';<b>秦始皇</b>东巡<b>洛阳</b>
class wordkey extends TTrie {
function b() {
$t = array_pop($this->buffer);
$this->buffer[] = "<b>$t</b>";
}
}
$p = new wordkey;
$p->set('秦始皇', 'b');
$p->set('洛阳', 'b');
$t = $p->match('秦始皇东巡洛阳');
echo join('', $t);
class TTrie {
protected $buffer = array();
protected $dict = array( array() );
protected $input = 0; //字符串当前偏移
protected $backtracking = 0; //字符串回溯位置
public $debug = 0;
public $savematch = 1;
function set($word, $action='') {
if(is_array($word)) {
foreach($word as $k=>$v) $this->set($k, $v);
return;
}
$p = count($this->dict);
$cur = 0; //当前节点号
foreach(str_split($word) as $c) {
if (isset($this->dict[$cur][$c])) { //已存在就下移
$cur = $this->dict[$cur][$c];
continue;
}
$this->dict[$p]= array(); //创建新节点
$this->dict[$cur][$c] = $p; //在父节点记录子节点号
$cur = $p; //把当前节点设为新插入的
$p++;
}
$this->dict[$cur]['acc'] = $action; //一个词结束,标记叶子节点
}
function getto($ch) {
$i =& $this->input; //字符串当前偏移
$p =& $this->backtracking; //字符串回溯位置
$len = strlen($this->doc);
$t = '';
$this->input++;
// while($this->input<$len && $this->doc{$this->input} != $ch) $t .= $this->doc{$this->input++};
// $t .= $this->doc{$this->input++};
do {
if($this->input >= $len) break;
$t .= $this->doc{$this->input};
}while($this->doc{$this->input++} != $ch);
return trim($t);
}
function match($s) {
$this->doc =& $s;
$this->buffer = array();
$ret = array();
$cur = 0; //当前节点,初始为根节点
$i =& $this->input; //字符串当前偏移
$p =& $this->backtracking; //字符串回溯位置
$i = $p = 0;
$s .= "\0"; //附加结束符
$len = strlen($s);
$buf = '';
while($i < $len) {
$c = $s{$i};
if(isset($this->dict[$cur][$c])) { //如果存在
$cur = $this->dict[$cur][$c]; //转到对应的位置
if(isset($this->dict[$cur][$s[$i+1]])) {//检查下一个字符是否也能匹配,长度优先
$i++;
continue;
}
if(isset($this->dict[$cur]['acc'])) { //是叶子节点,单词匹配!
if($buf != '') {
$this->buffer[] = $buf;
$buf = '';
}<