纯PHP,从复杂的HTML字符串中提取HTML内容


Pure PHP, extract HTML content from complex HTML string

我有一个复杂的HTML字符串,类似于:

some text <blockquote>main text<blockquote>quotation</blockquote>end of main text</blockquote> some other text

使用 PHP,我想提取第一个块引用的全部内容,即使这包括其他块引用:

main text<blockquote>quotation</blockquote>end of main text

困难的部分是我需要停止在右侧结束标签处切割字符串 - 属于第一个开始标签的那个(在本例中为最后一个 - 但这必须动态确定)。

这是我到目前为止的尝试:

<?php
$some_html = "<blockquote>main text<blockquote>quotation</blockquote>end of main text</blockquote>";
$result =  get_first_element_of_HTML_tag_name($some_html,'blockquote');
function get_first_element_of_HTML_tag_name($html_string,$tag_name) {
    $h = strtolower($html_string);
    $tag_open = "<" . $tag_name . ">";
    $tag_close = "</" . $tag_name . ">";
    $element_start = strpos($h,$tag_open)+strlen($tag_open);
    $element_end = strpos($h,$tag_close);
    $element = substr($h,$element_start,$element_end); // cut to first closing tag
    $element_s = $element;
    $i = 2;
    while ( strpos($element_s,"<blockquote") !== false ) { // as long as substring contains another opening tag
        // include another closing tag in the result
        $element = substr($h,$element_start,nth_strpos($h,$element_end,$i));
        $element_s = substr( $element_s, strpos($element_s,$tag_open)+strlen($tag_open), nth_strpos($element_s,strpos($element_s,$tag_close),$i));
        $i++;
    } 
    return $hs; // return complete first element with $tag_name
}
function nth_strpos($str, $substr, $n) { 
    $ct = 0; 
    $pos = 0; 
    while ( ( $pos = strpos($str, $substr, $pos) ) !== false ) { 
        if (++$ct == $n) { 
            return $pos; 
        } 
        $pos++; 
    } 
    return false; 
}  
php?>

$result返回空白...

我认为它卡在nth_strpos函数中的某个地方。

帮助甚至更简单的替代方案非常感谢!

正如Barmar所建议的,你可能应该使用DOM解析器。碰巧的是,PHP 5 附带了一个 DOM API,可以让您非常轻松地做到这一点。下面是一个示例:

$str = "some text <blockquote>main text<blockquote>quotation</blockquote>end of main text</blockquote> some other text";
$doc = new DOMDocument();
$doc->loadHTML($str);
$element = $doc->getElementsByTagName("blockquote")->item(0);
$innerHTML= '';
foreach ($element->childNodes as $child)
    $innerHTML .= $doc->saveXML($child);
echo $innerHTML;

输出:

main text<blockquote>quotation</blockquote>end of main text