我想使用 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 来完成这项任务。
首先,
我认为最好给该标签一个ID。
目录
<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 均衡器
function drinksCount(){
return $("#drinks li").children().length;
}
如果你想走正则表达式的方式..在不符合XHTML..尝试计算领先
/<td>/gm
希望对...