利用栈将html源码解析为节点树

<?php

/// 如何利用栈将html解析成节点树
/// 首先html是由一个个节点组成,最大的节点为<html></html>节点   她有两个子节点<head></head> 和<body></body>
/// 首先我们将<html>压入栈中 再将<head>压入栈中 遇到</head>出栈  <body>压入栈中 遇到</body> 出栈 最终<html>
/// 出栈 可以看出 出栈的一定是栈顶元素的子节点
/// 本程序假定html完全规范

/// todo  解决标签未闭合问题
/// todo  根据标签名访问
///       根据id访问
///       根据class访问
///      innerHtml 和 innerText

$tree_file = fopen("tree_file","w");
fclose($tree_file);

$siteurl="http://www.cnblogs.com/poissonnotes/archive/2010/05/28/1745996.html";
$str=get_content_by_url($siteurl);

$pattern="/<.*?>/";
$deep=0;

$global_false=true ;


$result=array();

$queue_id=0;

if(preg_match_all($pattern,$str,$matches))
{    
    $count=count($matches[0]);
    $matches=$matches[0];
    $queue=array();
    $error = fopen("string_tagss","a");
    
    for($i=0;$i<$count;$i++)
    {
        $temptag = $matches[$i];
        
        $node["Id"]=$i;
        $node["ChildId"]=array();
        $node["html_tag"]=$temptag;
        /// 如果是单标签
        if(is_single_tag($temptag))
        {
            //echo "this is a single tag:    ";
            //echo $temptag."\n";
            $str_deep=make_string($deep);
            fwrite($error,$str_deep."\t".$temptag."\n");


            if(!empty($queue))
            {
                $queue[count($queue)-1]["ChildId"][]=$queue_id;
            }
            $queue_id++;
            $result[]=$node;
            continue ;
        }
    
        /// 如果是结束标签
        if(is_end_tag($temptag))
        {    
            $temp_node = array_pop($queue);
            $queue[count($queue)-1]["ChildId"][]=$queue_id ;  // 出队的节点一定是栈顶元素的子孩子
            $queue_id++;
            $result[]=$temp_node;
        }
        else
        {    
            /// 如果是开始标签     
            $str_deep=make_string($deep);
            fwrite($error,$str_deep."\t".$temptag."\n");
            $queue[] = $node;
            $deep++;
        }
    }    

    if($global_false)
    {
        echo "ok\n" ;
    }
    else
    {
        echo "error\n" ;
    }
        
    //制作关系图谱  不包含结束标签
    //<html>
    //    <head>
    //            ............
    //        ............
    //    <body>
    //              ............
        //              ............

    $deep = 0;
    make_tree($result,$result[count($result)-1],$deep);

}

function is_single_tag($test_tag)
{
    $single_tags=array("meta","img","link","input","!DOCTYPE","area","base","basefont","embed","hr","br");
    $single_tag_string="(";
    foreach($single_tags as $single_tag)
    {
        $single_tag_string=$single_tag_string.$single_tag."|"  ;
    }
    $single_tag_string=$single_tag_string.")";
    $single_tag_string=str_replace("|)",")",$single_tag_string);
    $pattern="/\<".$single_tag_string.".*?\>/ i" ;
    
    if(preg_match($pattern,$test_tag))
    {
        return true ;
    }

    return false ;
}


function is_end_tag($test_tag)
{
    $pattern="/\<\/.*?\>/" ;
    if(preg_match($pattern,$test_tag))
    {
        return true ;
    }    
    return false ;
}


function is_exist_start_tag($queue,$temptag)
{
    $end_string=str_replace("/","",$temptag);
    $end_string=preg_replace("/\s*/","",$end_string);
    $end_string=strtolower($end_string);
    
    $count=count($queue);

    echo $count."\n";

    var_dump($queue);    
    
    for($i=$count-1;$i>=0;$i--)
    {    
        
        echo $i."\n";
        $string = $queue[$i]["html_tag"];        
        $string = preg_replace("/(<)(.*?)\s.*?(>)/",'$1$2$3',$string);    
        if(strtolower($string) == strtolower($end_string))
        {
            return true;
        }
    }        
    return false ;
}

function is_pear_tag($start_tag,$temptag)
{    
    $start_string=preg_replace("/(<)(.*?)\s.*?(>)/",'$1$2$3',$start_tag);    
    $end_string=str_replace("/","",$temptag);
    $end_string=preg_replace("/\s*/","",$end_string);    
    if(strtolower($start_string) == strtolower($end_string))
    {
        return true ;
    }
    else
    {
        return false ;
    }
}

function make_string($deep)
{
    $temstr="";
    for($i=0;$i<$deep;$i++)
        $temstr=$temstr."-";
    return $temstr;
}

function judge_tag($last_tag,$temptag)
{
    return false;
// 这里做一个判断 判断上一个标签是否能嵌套这个标签 比如
// <td> 不嵌套<td>
// <td> 不嵌套<tr>
// <tr> 不嵌套<tr>
// <tr> 不嵌套<table>   
// <table> 嵌套  <tr>  但不能嵌套其他 标签  
// <li> 不嵌套<li>
// <ul> 不嵌套<ul>
// <ol> 不嵌套<ol>    
// <head> 不能嵌套 <body>
}


function get_content_by_url($site_url)
{
    $ch=curl_init($site_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_ENCODING, "gzip");
    $content=curl_exec($ch);
    $content = str_replace("\r\n","",$content);
    $content = str_replace("\n\r","",$content);
    $content = str_replace("\n","",$content);
    $content = str_replace("\r","",$content);
    $content = preg_replace("/<!--\[if.*?<!\[endif\]-->/is","",$content);
    $content = preg_replace("/<!--.*?-->/is","",$content);
    $content = preg_replace("/<script(.*?)<\/script>/is","",$content);  
    $content = preg_replace("/<style(.*?)<\/style>/is","",$content);  

    $errores = fopen("baidu","w");
    fwrite($errores,$content) ;
    fclose($errores);
    
    return $content ;
}

function make_tree($result,$node,$deep)
{
    // 制作前缀 使得显示的层次分明
    $str="" ;
    for($i=0;$i<$deep;$i++)
    {
        $str=$str."--";    
    }
    echo $str;
    echo $node["html_tag"]."\n";

    $write_str = $str.$node["html_tag"]."\n";
    
    $tree_file = fopen("tree_file","a");
    fwrite($tree_file,$write_str);
    fclose($tree_file);

    $deep++;

    if(!empty($node["ChildId"]))
    {
        foreach($node["ChildId"] as $Child)
        {
            make_tree($result,$result[$Child],$deep) ;   ///递归
        }
    }
    else
    {
        return ;
    }
}
?>

转载于:https://my.oschina.net/qidis/blog/535004

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是利用实现任意两个节点的最近公共祖先的C语言代码: ```c #include <stdio.h> #include <stdlib.h> #define MAX_SIZE 100 // 定义二叉节点结构体 typedef struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; } TreeNode; // 定义结构体 typedef struct Stack { TreeNode *data[MAX_SIZE]; int top; } Stack; // 初始化 void initStack(Stack *s) { s->top = -1; } // 判断是否为空 int isEmpty(Stack *s) { return s->top == -1; } // 判断是否已满 int isFull(Stack *s) { return s->top == MAX_SIZE - 1; } // 入 void push(Stack *s, TreeNode *node) { if (isFull(s)) { printf("Stack is full!\n"); return; } s->data[++s->top] = node; } // 出 TreeNode *pop(Stack *s) { if (isEmpty(s)) { printf("Stack is empty!\n"); return NULL; } return s->data[s->top--]; } // 获取顶元素 TreeNode *getTop(Stack *s) { if (isEmpty(s)) { printf("Stack is empty!\n"); return NULL; } return s->data[s->top]; } // 判断节点是否在二叉 int isNodeInTree(TreeNode *root, TreeNode *node) { if (root == NULL) { return 0; } if (root == node) { return 1; } return isNodeInTree(root->left, node) || isNodeInTree(root->right, node); } // 查找任意两个节点的最近公共祖先 TreeNode *lowestCommonAncestor(TreeNode *root1, TreeNode *root2, TreeNode *p, TreeNode *q) { // 定义两个,用于存储从根节点节点p和节点q的路径 Stack stack1, stack2; initStack(&stack1); initStack(&stack2); // 从根节点开始遍历两棵,分别找到节点p和节点q,并将路径存储到对应的 TreeNode *cur1 = root1; while (cur1 || !isEmpty(&stack1)) { while (cur1) { push(&stack1, cur1); if (cur1 == p || cur1 == q) { break; } cur1 = cur1->left; } cur1 = getTop(&stack1); if (cur1->right && cur1->right != pop(&stack1)) { cur1 = cur1->right; } else { if (cur1 == p || cur1 == q) { break; } cur1 = NULL; } } TreeNode *cur2 = root2; while (cur2 || !isEmpty(&stack2)) { while (cur2) { push(&stack2, cur2); if (cur2 == p || cur2 == q) { break; } cur2 = cur2->left; } cur2 = getTop(&stack2); if (cur2->right && cur2->right != pop(&stack2)) { cur2 = cur2->right; } else { if (cur2 == p || cur2 == q) { break; } cur2 = NULL; } } // 如果节点p或节点q不在任何一棵,则它们没有公共祖先 if (!isNodeInTree(root1, p) || !isNodeInTree(root1, q) || !isNodeInTree(root2, p) || !isNodeInTree(root2, q)) { return NULL; } // 从顶开始比较两个的元素,找到最后一个相同的节点即为最近公共祖先 TreeNode *ancestor = NULL; while (!isEmpty(&stack1) && !isEmpty(&stack2)) { TreeNode *node1 = pop(&stack1); TreeNode *node2 = pop(&stack2); if (node1 == node2) { ancestor = node1; } else { break; } } return ancestor; } // 创建二叉 TreeNode *createBinaryTree(int arr[], int index, int n) { if (index >= n || arr[index] == -1) { return NULL; } TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode)); root->val = arr[index]; root->left = createBinaryTree(arr, 2 * index + 1, n); root->right = createBinaryTree(arr, 2 * index + 2, n); return root; } int main() { // 测试数据 int arr1[] = {3, 5, 1, 6, 2, 0, 8, -1, -1, 7, 4}; int arr2[] = {5, 6, 2, -1, -1, 7, 4}; TreeNode *root1 = createBinaryTree(arr1, 0, sizeof(arr1) / sizeof(arr1[0])); TreeNode *root2 = createBinaryTree(arr2, 0, sizeof(arr2) / sizeof(arr2[0])); TreeNode *p = root1->left; TreeNode *q = root2->left->right; // 查找任意两个节点的最近公共祖先 TreeNode *ancestor = lowestCommonAncestor(root1, root2, p, q); if (ancestor != NULL) { printf("The lowest common ancestor of node %d and node %d is %d.\n", p->val, q->val, ancestor->val); } else { printf("Node %d and node %d have no common ancestor.\n", p->val, q->val); } return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值