繁体   English   中英

PHP preg_match-匹配html元素

[英]PHP preg_match - matching html elements

好的,所以我有一个正则表达式试图与某些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”,则它将以“ /部分>”。

如果我的html看起来像这样,没有其他内容,则可以按预期工作:

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

问题是当我们稍后在html中有一个section元素时,它也有一个结尾/ section>。 例:

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

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

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

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

谢谢您的帮助!

是的,只需使用一个不满意的量词即可:

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM