首页 > 代码库 > php实现字典数标签,打标签给文章

php实现字典数标签,打标签给文章

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 = http://www.mamicode.com/$value;
$this->childNode[] = $node;
}
$node->id = $id;
return $node;
}

/* 查询子节点 */
public function searchChildNode($value){
foreach ($this->childNode as $k => $v) {
if($v->value =http://www.mamicode.com/= $value){
// 存在节点,返回该节点
return $this->childNode[$k];
}
}
return false;
}
}

php实现字典数标签,打标签给文章