How to strip Style Attributes from HTML Tags?

Roger picture Roger · Oct 12, 2011 · Viewed 9.6k times · Source

I want to remove all styles from tags with PHP.

For example.

Original:

<body style="color:back;">

Final:

<body>

Here's a example:

$body_htm='<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>[Some Title] some text...</title>
</head>
<body style="background-color: #F2F2F2; color: #222; font-family: georgia,serif; letter-spacing: -0.01em; line-height: 1.25; margin-bottom: 0.55em; font-size: 1.2em;">
<div style="background-color: #F2F2F2; border: 2px dotted #333; padding: 55px 0 55px 55px;">
<div style="background-color: #F2F2F2; width: 400px;">
<p style="margin-bottom:110px;"><b>Hello!!!</b></p>';

It should return this:

<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>[Some Title] some text...</title>
</head>
<body>
<div>
<div>
<p><b>Hello!!!</b></p>';

Any ideas?

Answer

fallenland picture fallenland · Oct 12, 2011

A very simple replace will probably do:

preg_replace( '/style=(["\'])[^\1]*?\1/i', '', $subject, -1 );

Hope this helps