How To Remove Specific Class And Attributes From Html Tags Using PHP?

I recommend PHP Simple HTML DOM Parser, let you manipulate HTML in a very easy way!. You can find tags on an HTML page with selectors just like jQuery.
$html = "<div>
<span class="test1 test2 test3" data-id="5"  >text 1</span><br />
<span class="test1 test3 test2">text 4</span></div>";
If just want to either empty or remove any class that has "test2" in it and remove attributes like "data-id". You can use PHP Simple HTML DOM Parser to remove specific class and attribute from HTML tags like below. In order to delete specific class from HTML tags, you can use SIMPlE PHP DOM Parser and preg_replace function. You can remove attributes easily using removeAttribute method.
// Find all elements with the class test2 attribute
foreach($html->find('[class=test2]') as $e){
    $e->removeAttribute("data-id"); //remove attribute 
    $e->class = preg_replace("/(?:^|\s)editable(?:\s|$)/msi", " ", $e->class);
}

echo $html;
The outcome
<div>
<span class="test1 test3">text 1</span><br />
<span class="test1 test3">text 4</span></div>

If you guys know any other efficient way, do share for our users. :)

Comments

Popular Posts