PHP How to remove the style attribute from HTML tags only in the img tag?

advertisements

I usually use this code in order to remove style attributes from HTML tags.

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

However, now i want to remove style attributes from HTML tags only in an IMG tag.

How can i do that?


If you have to manipulate HTML in PHP, it is safer to use a DOM parser. As an example, here is some code based on DOMDocument/ DOMXPath to get all img tags having style attributes and remove only those attributes:

$html = <<<DATA
<body>
<span style="new">Don't modify it</span>
<span style="old">Don't modify it</span>
<img style="Remove-me" src="img.jpg">
<img src="img.jpg" title="Don't modify it">
</body>
DATA;

// Initializing the DOM tree with an HTML string above
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$xpath = new DOMXPath($dom);
$imgs = $xpath->query('//img[@style]'); // Fetch all img tags having style attribute

foreach($imgs as $img) {
   $img->removeAttribute('style'); // Remove the style attribute
}

echo $dom->saveHTML(); // Show the modified HTML

See the PHP demo.