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

纯PHP,从复杂的HTML字符串中提取HTML内容,php,Php,我有一个复杂的HTML字符串,类似于: some text <blockquote>main text<blockquote>quotation</blockquote>end of main text</blockquote> some other text 我想使用PHP提取第一个blockquote的全部内容,即使其中包括其他blockquote: main text<blockquote>quotation</block

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

some text <blockquote>main text<blockquote>quotation</blockquote>end of main text</blockquote> some other text
我想使用PHP提取第一个blockquote的全部内容,即使其中包括其他blockquote:

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返回为空

我想它卡在了第n个strps函数的某个地方


非常感谢您的帮助或更简单的选择

正如Barmar所建议的,您可能应该使用DOM解析器。碰巧PHP5附带了一个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

为什么不使用DOM解析器库?他们已经为您解决了这个问题。同意,编写HTML解析器绝非易事,请尝试使用regex/s。@elclandrs no!不要尝试使用正则表达式。使用DOM解析器。DOMDocument是最好的方法。没有头痛,只是轻微的学习曲线。不要重新发明轮子,除非你的轮子比现有的更好