使用php从字符串中删除带有类名的div

Ire*_* T. 0 javascript php regex preg-match-all preg-match

我需要从字符串中删除特定的div.

我的代码是:

$varz = "<div class="post-single">
<p> Hello all! </p>
<div class="ad">I want to remove this div</div>
</div>";

$varzfinal = preg_replace('/<div class="ad">.+<\/div>/siU', '', $varz); 
echo $varzfinal;
Run Code Online (Sandbox Code Playgroud)

我需要删除它: <div class="ad">I want to remove this div</div>

实现这一目标的最佳方法是什么?

rev*_*evo 6

我们都很有耐心.正则表达式用于specefic案例.这里PHP社区为我们制作了DOMDocument.那么为什么不用它最好的呢?!

<?php
    $varz = <<< EOT
    <div class="post-single">
    <p> Hello all! </p>
    <div class="ad">I want to remove this div</div>
    </div>
EOT;

    $d = new DOMDocument();
    $d->loadHTML($varz);
    $s = new DOMXPath($d);
    foreach($s->query('//div[contains(attribute::class, "ad")]') as $t )
        $t->parentNode->removeChild($t);

    echo $d->saveHTML();
Run Code Online (Sandbox Code Playgroud)