1. 程式人生 > >php實現字典數標簽,打標簽給文章

php實現字典數標簽,打標簽給文章

-- pre end har node nod 文章 search arr

class Tag
{
public static function addTag($str, $arr)
{
$head = new Node; // 樹的head
self::addString($head,$arr);
exit;
$str = trim($str);
$result = self::searchString($head,$str);
$result = array_unique($result);
return $result;
}
/* 添加字符串 */
private static function addString(&$head, $arr = []){
foreach($arr as $key => $item) {
$node = null;
for ($i=0; $i < mb_strlen($item); $i++) {
$char = mb_substr($item,$i,1);
if($char != ‘‘){
$is_end = $i != (mb_strlen($item) - 1) ? false : true;
if($i == 0){
if($is_end){
$node = $head->addChildNode($char, $key);
}else{
$node = $head->addChildNode($char, 0);
}
}else{
if($is_end){
$node = $node->addChildNode($char, $key);
}else{
$node = $node->addChildNode($char, 0);
}
}
}
}
}
}

/* 搜索 */
private static function searchString($node, $str){
$head = $node;
$result = [];
$depth = 0;
for ($i=0; $i < mb_strlen($str); $i++) {
$char = mb_substr($str,$i,1);
if($char != ‘\0‘){
$node = $node->searchChildNode($char);
// print_r($node);
if($node === false){
//沒有找到
$i=$i-($depth-1);
$depth=0;
$node = $head;
}elseif($node->id){
// 找到了
$result[]=$node->id;
$node = $head;
$depth = 0;
}swo
$depth++;
}
}
return $result;
}

///* 獲取所有字符串--遞歸 */
private static function getChildString($node, $str_array = array(), $str = ‘‘){
if($node->id){
$str_array[] = $node->id;
}
if(empty($node->childNode)){
return $str_array;
}else{
foreach ($node->childNode as $k => $v) {
$str_array = getChildString($v, $str_array, $str . $v->value);
}
return $str_array;
}
}
}

class Node{
public $value; // 節點值
// public $is_end = false; // 是否為結束--是否為某個標簽的結束節點
public $id = 0; // 標簽id
public $childNode = array(); // 子節點

/* 添加孩子節點--註意:可以不為引用函數,因為PHP對象賦值本身就是引用賦值 */
public function &addChildNode($value, $id = 0){
$node = $this->searchChildNode($value);
if(empty($node)){
// 不存在節點,添加為子節點
$node = new Node();
$node->value = $value;
$this->childNode[] = $node;
}
$node->id = $id;
return $node;
}

/* 查詢子節點 */
public function searchChildNode($value){
foreach ($this->childNode as $k => $v) {
if($v->value == $value){
// 存在節點,返回該節點
return $this->childNode[$k];
}
}
return false;
}
}

php實現字典數標簽,打標簽給文章