使用 Regex 从内容中删除一个 div

Stripping one div out of content with Regex

我正在尝试从内容块中删除一个特定的 div(及其内部内容),但是它不太有效。

正则表达式:

/<div class="greybackground_desktop".*>(.*)<\/div>/s

Preg_replace:

preg_replace($pattern, "", $holder, -1, $count );

现在,正则表达式确实去除了我的 div,但是如果有任何其他后续关闭 div 标记,它也会去除它们以及其中的任何其他内容。

例如

<p>some random text</p>

<div class="greybackground_desktop" style="background-color:#EFEFEF;">
<!-- /49527960/CSF_Article_Middle -->
<div style="padding-bottom:10px; padding-top: 10px; text-align:center;" id='div-gpt-ad-1441883689230-0'>
<script type='text/javascript'>
googletag.cmd.push(function() { googletag.display('div-gpt-ad-1441883689230-0'); });
</script>
</div>
</div>

<p>some more text</p>

<div><p>example of content that will be incorrectly removed</p></div>

<p>Text that follows</p>

这将导致以下输出:

some random text

Text that follows

我想看的是:

some random text

some more text

example of content that will be incorrectly removed

Text that follows

有什么想法吗?

正确的方法是使用像 DOMDocument 这样的 Html 解析器,下面是一个例子:

$holder = <<< LOL
<p>some random text</p>
<div class="greybackground_desktop" style="background-color:#EFEFEF;">
<!-- /49527960/CSF_Article_Middle -->
<div style="padding-bottom:10px; padding-top: 10px; text-align:center;" id='div-gpt-ad-1441883689230-0'>
<script type='text/javascript'>
googletag.cmd.push(function() { googletag.display('div-gpt-ad-1441883689230-0'); });
</script>
</div>
</div>
<p>some more text</p>
<div><p>example of content that will be incorrectly removed</p></div>
<p>Text that follows</p>
LOL;
$dom = new DOMDocument();
//avoid the whitespace after removing the node
$dom->preserveWhiteSpace = false;
//parse html dom elements
$dom->loadHTML($holder);
//get the div from dom
if($div = $dom->getElementsByTagName('div')->item(0)) {
   //remove the node by telling the parent node to remove the child
   $div->parentNode->removeChild($div);
   //save the new document
   echo $dom->saveHTML();
}

Ideone DOMDocument Demo



如果你真的想使用正则表达式,请使用 lazy 一个 .*? 而不是 greedy .*,即:

$result = preg_replace('%<div class="greybackground_desktop".*?</div>\s+</div>%si', '', $holder);

Ideone Demo


阅读更多关于正则表达式重复的内容,特别是“懒惰而不是贪婪

http://www.regular-expressions.info/repeat.html


改用 DOMDocument 这样的解析器。考虑这段代码:

<?php
$dom = new DOMDocument();
$dom->loadHTML($your_html_here);

$xpath = new DOMXpath($dom);

foreach ($xpath->query("//div[@class='greybackground_desktop']") as $div)
    $div->parentNode->removeChild($div);

echo $dom->saveHTML();
?>

该脚本会加载您的 html,查找带有 div.greybackground_desktop 的元素并将其删除。 演示 可在 ideone.com.

上找到