如何使用preg_replace删除整个div [英] How to remove entire div with preg_replace
问题描述
好吧,这是WordPress问题,可悲的是,它更深了一点,我需要删除父div及其内部的每个表示形式:
Ok, as it is WordPress problem and it sadly goes a little deeper, I need to remove each representation of parent div and its inside:
<div class="sometestclass">
<img ....>
<div>.....</div>
any other html tags
</div><!-- END: .sometestclass -->
我唯一的想法是匹配所有以以下内容开头的内容:
The only idea I have is to match everything that starts with:
<div class="sometestclass">
结尾为:
<!-- END: .sometestclass -->
介于两者之间(无论如何,我都可以标记父div的结尾,这只是一个示例). 任何人都知道如何使用它:
with all that is between (I can tag the end of parent div anyway I want, this is just a sample). Anybody have an idea how to do it with:
<?php $content = preg_replace('?????','',$content); ?>
推荐答案
我不会使用正则表达式.相反,我将使用 DOMDocument 类.只需找到该类的所有div
元素,然后将其从其父级中删除:
I wouldn't use a regular expression. Instead, I would use the DOMDocument class. Just find all of the div
elements with that class, and remove them from their parent(s):
$html = "<p>Hello World</p>
<div class='sometestclass'>
<img src='foo.png'/>
<div>Bar</div>
</div>";
$dom = new DOMDocument;
$dom->loadHTML( $html );
$xpath = new DOMXPath( $dom );
$pDivs = $xpath->query(".//div[@class='sometestclass']");
foreach ( $pDivs as $div ) {
$div->parentNode->removeChild( $div );
}
echo preg_replace( "/.*<body>(.*)<\/body>.*/s", "$1", $dom->saveHTML() );
这将导致:
<p>Hello World</p>
这篇关于如何使用preg_replace删除整个div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!