1

我有一个复杂的 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 函数的某个地方。

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

4

1 回答 1

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
于 2013-10-11T00:00:50.127 回答