PHP preg_match - 匹配html元素

时间:2013-06-01 01:17:24

标签: php html regex html-parsing preg-match

好的,所以我有一个正则表达式,我试图用来匹配某些html文件中的某个模式。这是preg_match语句:

preg_match('@<'.$htmlElementType.' id\s*=\s*"{{ALViewElement_'.$this->_elementId.'}}".*>[\s\S]*</'.$htmlElementType.'(>)@i', $htmlString, $newMatches, PREG_OFFSET_CAPTURE)

要清楚,这是尝试匹配id为{{ALViewElement _。*}}的html元素,但它还需要以结束标记结束自己,例如,如果$ htmlElementType为“section”,它将结束在“/ section&gt;”中。

如果我的html看起来就像这样,没有别的东西,它按预期工作:

<section id="{{ALViewElement_resume}}">
            <!--{{RESUME_ADD_CHANGE_PIECE}}-->
            <!--{{RESUME}}-->
        </section>

问题是我们稍后在html中有一个section元素,它还有一个结束/部分&gt;。例如:

<section id="{{ALViewElement_resume}}">
            <!--{{RESUME_ADD_CHANGE_PIECE}}-->
            <!--{{RESUME}}-->
        </section>
        <div>

        </div>
        <section>
            HEY THIS IS ME
        </section>

在这种情况下,完整的马赫就是上面的一切。但我希望它停止在那打开我的第一个。这很重要,因为稍后在我的代码中我需要最后一个&gt;的位置。在那个结束标记中。

我有什么想法可以改变这个正则表达式吗?

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

是的,只是使用一个不合理的量词:

preg_match('@<'.$htmlElementType.' id\s*=\s*"{{ALViewElement_'.$this->_elementId.'}}".*?>[\s\S]*?</'.$htmlElementType.'(>)@i', $htmlString, $newMatches, PREG_OFFSET_CAPTURE)

另一种方式:使用DOMDocument:

$html = <<<LOD
<section id="{{ALViewElement_resume}}">
        <!--{{RESUME_ADD_CHANGE_PIECE}}-->
        <!--{{RESUME}}-->
</section>
<div>

</div>
<section>
    HEY THIS IS ME
</section>
LOD;
$doc= new DOMDocument();
@$doc->loadHTML($html);
$node = $doc->getElementById("{{ALViewElement_resume}}");

$docv = new DOMDocument();
$docv->appendChild($docv->importNode($node, TRUE));
$result = $docv->saveHTML();
echo htmlspecialchars($result);