user3660449
user3660449

Reputation: 15

Removing attributes from HTML Tags with PHP

How to remove table's attributes like height, border-spacing and style="";

<table style="border-collapse: collapse" border="0" bordercolor="#000000" cellpadding="3" cellspacing="0" height="80" width="95%">

to this -->

<table>

strip_tags works for ripping tags off, but what about preg_replace?

FYI: loading stuff from database and it has all these weird styling and I want to get rid of them.

Upvotes: 1

Views: 2067

Answers (1)

GuCier
GuCier

Reputation: 7415

If you really want to use preg_replace, this is the way to go, but keep in mind that preg_replace isn't reliable

$output = preg_replace('/(<[^>]+) style=".*?"/i', '$1', $html);

I recommend you to use php DOM that exists for this kind of operation :

// load HTML into a new DOMDocument
$dom = new DOMDocument;
$dom->loadHTML($html);

// Find style attribute with Xpath
$xpath = new DOMXPath($dom);
$styleNodes = $xpath->query('//*[@style]');

// Iterate over nodes and remove style attributes
foreach ($styleNodes as $styleNode) {
  $styleNode->removeAttribute('style');
}

// Save the clean HTML into $output
$output = $dom->saveHTML();

Upvotes: 1

Related Questions