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

时间:2013-10-10 23:33:19

标签: php

我有一个类似于:

的复杂HTML字符串
some text <blockquote>main text<blockquote>quotation</blockquote>end of main text</blockquote> some other text

使用PHP我想提取第一个blockquote的全部内容,即使它包含其他blockquotes:

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函数的某个地方。

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

1 个答案:

答案 0 :(得分:0)

正如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