user6803164 user6803164 - 24 days ago 8
CSS Question

Remove a div of a particular class

I have some divs:

<h4>Ruby on Rails</h4>
<div class="progress-bar green">
<span style="width: 90%"></span>
</div>
<h4>HTML/CSS</h4>
<div class="progress-bar orange">
<span style="width: 80%"></span>
</div>
<h4>PHP</h4>
<div class="progress-bar orange">
<span style="width: 60%"></span>
</div>
<h4>Javascript</h4>
<div class="progress-bar red">
<span style="width: 40%"></span>
</div>


I want to use php to remove any div appearing with class "progress-bar" in html code of a page.
Like:

If I have file_html.php with some code, I will get it's html code using this line:

$html = file_get_contents('file_html.php');


And now I want to remove the progress-bar divs appearing in the code.
Is this possible, if yes how can I solve problem?
Thanks in advance.

Answer

I would suggest using the DOMDocument class

Since you cannot remove an element from a list while iterating, then build up a to-be-removed array and drop those after searching.

Here's a working fiddle.

<?php
$html = file_get_contents('file_html.php');

$dom = new DOMDocument();
$dom->loadHTML($html);

$divs = $dom->getElementsByTagName('div');
foreach ($divs as $div) {
    $class = $div->getAttribute('class');
    if (strpos($class, 'progress-bar') !== false) {
        $domElemsToRemove[] = $div;
    }
}

foreach( $domElemsToRemove as $domElement ){ 
    $div->parentNode->removeChild($domElement); 
}

echo $dom->saveHTML();

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><h4>Ruby on Rails</h4>

<h4>HTML/CSS</h4>

<h4>PHP</h4>

<h4>Javascript</h4>
</body></html>