[英]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.