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

來源:互聯網
上載者:User

標籤:不為   each   private   ==   ati   字元   nod   node   return   

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實現字典數標籤,打標籤給文章

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.