I'm not too good with regular expressions, but with PHP I'm wanting to remove the style
attribute from HTML tags in a string that's coming back from TinyMCE.
So change <p style="...">Text</p>
to just vanilla <p>Test</p>
.
How would I achieve this with something like the preg_replace()
function?
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 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="..."
.