【问题标题】:Count all HTML tags in page PHP计算页面 PHP 中的所有 HTML 标签
【发布时间】:2010-07-06 07:25:19
【问题描述】:

我花时间在正则表达式上来解决这个问题,但没有结果 我尝试使用 PHP 5.3 解决这个问题 类似信息 - 页面中重复的次数以及页面中所有标签的信息。

【问题讨论】:

  • 请发布您尝试过的内容。如果您只想计算 dom 元素的数量,您可能会从 javascript 中获得更好的结果,但 php 可以使用 libxml 来实现...假设它是有效的 xhtml。
  • 如果你是从 PHP 做的,你应该使用DOMDocument class。在此处查看 Gordon 的答案:str_replace within certain html tags only
  • 我尝试使用 reg exp 和 substr 逻辑来解决这个问题,接下来将所有页面转换为 1 个长字符串查找 html 标记并在删除所有内容并计数下一个后在文本中继续所有其他内容

标签: php html regex


【解决方案1】:

不幸的是,以目前的形式,您的问题几乎无法理解。请尝试更新它并更具体。如果你想统计一个页面中的所有 HTML 标签,你可以这样做:

$HTML = <<< HTML
<html>
    <head>
        <title>Some Text</title>
    </head>
    <body>
        <p>Hello World<br/>
            <img src="earth.jpg" alt="picture of earth from space"/>
        <p>
        <p>Counting Elements is easy with DOM</p>
    </body>
</html>
HTML;

用 DOM 计算所有 DOMElements:

$dom = new DOMDocument;
$dom->loadHTML($HTML);
$allElements = $dom->getElementsByTagName('*');
echo $allElements->length;

上面会输出8,因为DOM中有八个元素。如果你还需要知道元素的分布,你可以这样做

$elementDistribution = array();
foreach($allElements as $element) {
    if(array_key_exists($element->tagName, $elementDistribution)) {
        $elementDistribution[$element->tagName] += 1;
    } else {
        $elementDistribution[$element->tagName] = 1;
    }
}
print_r($elementDistribution);

这会返回

Array (
    [html] => 1
    [head] => 1
    [title] => 1
    [body] => 1
    [p] => 2
    [br] => 1
    [img] => 1
)

请注意,getElementsByTagName 仅返回 DOMElements。它不考虑结束标签,也不返回其他 DOMNode。如果您还需要计算结束标记和其他节点类型,请考虑改用XMLReader

【讨论】:

    【解决方案2】:
    $testHTML = file_get_contents('index.html');
    
    $search = preg_match_all('/<([^\/!][a-z1-9]*)/i',$testHTML,$matches);
    
    echo '<pre>';
    var_dump($matches[1]);
    echo '</pre>';
    

    为您提供所有标签的数组。一旦数据在数组中,您就可以使用所有标准的 PHP 数组函数 - 例如array_count_values() - 提取你想要的细节......虽然你并没有真正说出你想要关于 html 标签的什么信息

    将 array_count_values() 与 preg_match_all() 的结果一起使用:

    echo '<pre>';
    var_dump(array_count_values($matches[1]));
    echo '</pre>';
    

    给予

    array(5) {
      ["html"]=>
      int(1)
      ["head"]=>
      int(1)
      ["title"]=>
      int(1)
      ["body"]=>
      int(1)
      ["h1"]=>
      int(2)
    }
    

    这是你想要的吗?

    【讨论】:

    • 信息需要像 div - 5 a - 7 p - 22 Maby DOMDocument 不是这个任务的最佳解决方案?
    • 是的,非常感谢,这是我长期折磨的问题 很好的答案 非常感谢
    【解决方案3】:

    我建议你结帐simple html dom

    http://simplehtmldom.sourceforge.net/manual.htm

    【讨论】:

    • 它是一个用于 1 个简单任务的大包:/
    猜你喜欢
    • 1970-01-01
    • 2021-04-10
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多