如何使用PHP DOMDocument计算特定类的div [英] How to count div of a specific class using PHP DOMDocument
本文介绍了如何使用PHP DOMDocument计算特定类的div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个html字符串
I have a html string
html_string = '<div class="quote" post_id="48"
style="border:1px solid #000;padding:15px;margin:15px;" user_id="1"
user_name="rashidfarooq">This is not True</div>
<div class="quote" post_id="49" style="border:1px
solid #000;padding:15px;margin:15px;" user_id="1"
user_name="rashidfarooq">This is good for me</div>
<div class="genuine" post_id="49" style="border:1px
solid #000;padding:15px;margin:15px;" user_id="1"
user_name="rashidfarooq">This is good for me</div>';
我想算出我尝试过的类名= quote
的div
I want to count the div having class name = "quote" I have tried
$dom = new DOMDocument;
$dom->loadHTML($html_string);
$divs = $dom->getElementsByTagName('div');
$length = $divs->length;
但是$ length给出了div的总数。我如何只计数具有类名称= quote的div。有任何PHP本机函数可以做到这一点。
But the $length gives the total number of divs. How can I count only the divs having class name = "quote". Is there any PHP Native function that can do that.
推荐答案
似乎没有本机的domdocument函数,但这是自己写起来很容易:
There doesnt seem to be a native domdocument function for that, but it's easy to write it yourself:
function getElementsByClassName($elements, $className) {
$matches = array();
foreach($elements as $element) {
if (!$element->hasAttribute('class')) {
continue;
}
$classes = preg_split('/\s+/', $element->getAttribute('class'));
if ( ! in_array($className, $classes)) {
continue;
}
$matches[] = $element;
}
return $matches;
}
$dom = new DOMDocument;
$dom->loadHTML($html_string);
$divs = getElementsByClassName($dom->getElementsByTagName('div'), 'quote');
$length = $divs->length;
这篇关于如何使用PHP DOMDocument计算特定类的div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文