Martin Bean Martin Bean - 1 month ago 11x
PHP Question

Remove style attribute from HTML tags

I'm not too good with regular expressions, but with PHP I'm wanting to remove the

attribute from HTML tags in a string that's coming back from TinyMCE.

So change
<p style="...">Text</p>
to just vanilla

How would I achieve this with something like the


The pragmatic regex (<[^>]+) style=".*?" will solve this problem in all reasonable cases. The part of the match that is not the first captured group should be removed, like this:

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

Match a < followed by one or more "not >" until we come to space and the the style="..." part. The /i makes it work even with STYLE="...". Replace this match with $1, which is the captured group. It will leave the tag as is, if the tag doesn't include style="...".