Irene T.
Irene T.

Reputation: 1393

remove a div with class name from a string with php

I need to remove a specific div from a string.

My code is:

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

I need to remove this: <div class="ad">I want to remove this div</div>

What's the best way to achieve this?

Upvotes: 0

Views: 3282

Answers (2)

aks.
aks.

Reputation: 386

Here is the fixed PHP/regex, works for class "ad" and "ad1" or any other number:

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

<div class="ad2">I want to remove this div</div>
<div class="a">I dont want to remove this div</div>
<div> cool </div>
</div>';

$varzfinal = preg_replace('/<div class="ad(\d*)?">.+<\/div>/siU', '', $varz); 
echo $varzfinal;
?>

To fix the encoding add <meta charset="utf-8"> in the section.

Upvotes: 0

revo
revo

Reputation: 48721

We are all patient. Regular Expressions are built to be used on specefic cases. Here PHP community made for us DOMDocument. So why not use the best out of it?!

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

Upvotes: 8

Related Questions