【问题标题】:How to count a specific tags ex. <li> tag or <p> tag [duplicate]如何计算特定标签前。 <li> 标签或 <p> 标签 [重复]
【发布时间】:2013-10-19 10:39:35
【问题描述】:

我想使用 php 来计算我的 html 代码中的每个 li 标签,这样我就可以知道是否缺少结束标签 (if the count of opening tags != the count of closing tags)

是否可以使用 php 正则表达式

这是我的第一个 html 代码:

<ul>
    <li>Coffee</li>
    <li>Tea  <!-- closing tag is missing -->
    <li>Milk</li>
    <li>Orange</li>
</ul>

那么if the count of opening tags == the count of closing tags呢,但是表单本身有错误:

<ul>
    <li>Coffee</li>
    </li>  <!-- opening tag is missing -->
    <li>Milk</li>
    <li>Orange</li>
    <li>Tea  <!-- closing tag is missing -->
</ul>

最后,除了这种思考如何解决问题的方式之外,还有没有更有效的方式使用 php 来完成这项任务

【问题讨论】:

  • 前面说了很多次,我认为你不应该用正则表达式解析html。
  • 如果您想诊断可能无效的 HTML,也许 Tidy 可以帮助您:php.net/manual/en/tidy.diagnose.php
  • @KaarelKont-Kontson 这就是我提到的原因:注意:最后,.....
  • 恕我直言:这不是无效的 html.. 它只是不符合 xhtml 格式
  • 你为什么不把它解析为xml并检查验证呢?使用 XMLReader? html 是 xml 结构。我不是 php 程序员,你可以看到这个例子并对其进行测试:example

标签: php html regex


【解决方案1】:

首先,我认为最好给该标签一个 id。

HTML

<ul id="drinks">
    <li>Coffee</li>
    <li>Tea  //closing tag is missing
    <li>Milk</li>
    <li>Orange</li>
</ul>

php方式

<?php
    $doc = new DOMDocument();
    $xml = $str->asXML();  // $str is your html string
    $doc->loadXML($xml);
    $bar_count = $doc->getElementsByTagName("ul")->length;
    echo $bar_count;
?>

<?php
    $elem = new SimpleXMLElement($str); // $str is your html string
    foreach ($elem as $ul) {
        printf("%s has got %d children.\n", $ul['id'], $ul->count());
    }
?>

<?php
   $DOM = new DOMDocument;
   $DOM->loadHTML($str); // $str is your html string
   echo $DOM->getElementsByTagName('ul')->length;
?>

javascript方式是这样的:

function drinksCount(){
    return document.getElementById("drinks").childNodes.length;
}

jquery 的匿名方式是

function drinksCount(){
    return $("ul li").children().length;    
}

有一个被调用的 id eq

function drinksCount(){
    return $("#drinks li").children().length;    
}

如果你想走正则表达式的方式.. 如果不符合 xhtml.. 尝试计算前导

/<td>/gm

希望对你有帮助……

【讨论】:

  • 他要求 php 解决方案。
  • 我暗示他要求一个正则表达式..我想展示替代品..
  • @AlexTape 感谢您给我不同的方法。我尝试了 Dom 方法,我得到了DOMDocument::loadHTML(): Unexpected end tag : li in Entity, line: ... 我怎样才能抓住它并删除那个额外的 li 标签?
  • @Dvir 我不是大师...但是如果 op 在处理 dom 时要求使用正则表达式解决方案,那么必须预期会出现与 domdoc 相关的答案...op 必须确定正则表达式是否合适,因为有时正则表达式比使用 domdoc 更容易/更快/更好。一切都有分量,但这并不意味着 domdoc 不是正确的答案。
  • @usama,您可以通过在调用前加上 @ 即 @DOMDocument::loadHTML() 来抑制错误。如果错误无关紧要,请抑制它并继续
猜你喜欢
  • 2021-10-12
  • 2012-03-13
  • 1970-01-01
  • 2014-07-25
  • 2016-08-15
  • 2018-05-07
  • 2016-01-20
  • 1970-01-01
  • 2022-12-17
相关资源
最近更新 更多