Baidu Encyclopedia keyword link is how to achieve it
Baidu Encyclopedia keyword with a link. I'm thinking of a few key words, just a simple replacement to link to it. But Baidu keyword is more ruthless, may millions on thousands. If you replace the tens of thousands of times, then the efficiency is too low. How can such a function be implemented? Thank you!
Report:
keyword links
------Solution--------------------
Okay, I'll send it again.
Include ' ttrie.php ';
Class Wordkey extends Ttrie {
Function B () {
$t = Array_pop ($this->buffer);
$this->buffer[] = "$t";
}
}
$p = new Wordkey;
$p->set (' Qin Shihuang ', ' B ');
$p->set (' Luoyang ', ' B ');
$t = $p->match (' Qin shihuang East patrol Luoyang ');
echo Join ("', $t);
Qin ShihuangEast Patrol
Luoyang
ttrie.php
Class Ttrie {
Protected $buffer = Array ();
Protected $dict = Array (array ());
protected $input = 0; String Current Offset
protected $backtracking = 0; String backtracking position
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; Current node number
foreach (Str_split ($word) as $c) {
if (Isset ($this->dict[$cur [$c])) {//already exists Move down
$cur = $this->dict[$cur] [$c];
Continue
}
$this->dict[$p]= Array (); Create a new node
$this->dict[$cur] [$c] = $p; Record child node number on parent node
$cur = $p; Sets the current node to the newly inserted
$p + +;
}
$this->dict[$cur [' acc '] = $action; A word ends, marks the leaf node
}
function Getto ($ch) {
$i =& $this->input; String Current Offset
$p =& $this->backtracking; String backtracking position
$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; The current node, initially the root node
$i =& $this->input; String Current Offset
$p =& $this->backtracking; String backtracking position
$i = $p = 0;
$s. = "n"; Append Terminator
$len = strlen ($s);
$buf = ";
while ($i < $len) {
$c = $s {$i};
if (Isset ($this->dict[$cur [$c])) {//if present
$cur = $this->dict[$cur] [$c]; Go to the corresponding location
if (Isset ($this->dict[$cur] [$s [$i +1]]) {//check if the next character matches, length first
$i + +;
Continue
}
if (Isset ($this->dict[$cur [' ACC '])) {//Is leaf node, Word match!
if ($buf! = ") {
$this->buffer[] = $buf;
$buf = ";
}
if ($this->savematch) $this->buffer[] = substr ($s, $p, $i-$p + 1); Take out the matching position and match the word