0

我有一个 html 字符串

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

    $dom = new DOMDocument;
    $dom->loadHTML($html_string);
    $divs = $dom->getElementsByTagName('div');
    $length = $divs->length;

但是 $length 给出了 div 的总数。我怎样才能只计算类名 = “quote”的 div。是否有任何 PHP Native 函数可以做到这一点。

4

2 回答 2

2

似乎没有本机 domdocument 功能,但是自己编写很容易:

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;
于 2013-03-27T07:56:35.007 回答
0

尝试

$DOMResponse = new \DOMDocument();
$DOMResponse->loadXML($data);
$xpath = new \DOMXPath($DOMResponse);
$length = $xpath->query('/*[@class="quote"]')->length; 

quote您要查询的课程在哪里

笔记

如果您还想在之前过滤 div,则必须在之前查询 div,然后应用我在上面建议的查询

像这样的东西

$length = $xpath->query('//div[@class="quote"]')->length;
于 2013-03-27T07:59:11.040 回答