views:

374

answers:

6
+1  A: 

You could use regular expressions:

$text = preg_relace('#<(.+?)style=(:?"|\')?[^"\']+(:?"|\')?(.*?)>#si', '<a\\1 \\2>', $text);
Crozin
see this http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags
TTT
Thanks, but that line doesnt work. I get the error:Parse error: syntax error, unexpected '[' in ... (etc filename)
Onion
I've forgotten to add escape chars before `'` ;)
Crozin
Hi Crozin, not sure where I should add an escape character? Do you mean a \ ?
Onion
@Alon, see the second answer on that page: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1733489#1733489 . He has some known HTML which is being reliably generated, so a regex is not a bad solution here.
nickf
A: 

Couldn't you just use strip_tags and leave in the tags you want eg <p>, <strong> etc?

niggles
No, because I want to keep the <p> tags, but I don't want any with inline styles, eg <p style="color:#fff;"> It's the inline style I want to remove without removing the <p>
Onion
+2  A: 

Use HtmlPurifier

troelskn
I could use a third party, but I was hoping there was a simpler solution, like using one line of regex
Onion
Sure. Just be aware of the risks - There *will* be edge cases with a regexp.
troelskn
+2  A: 

I quickly put this together, but for 'inline styles' (!) you will need something like

$text = preg_replace('#(<[a-z ]*)(style=("|\')(.*?)("|\'))([a-z ]*>)#', '\\1\\6', $text);
jakenoble
This one works perfectly, thanks jakenoble!
Onion
A: 

Why don't you just overwrite the tags. So you will have clean tags without inline styling.

Sinan
A: 

I found this class very useful for doing strip attributes (especially where there's crazy MS Word formatting all through the text):

http://semlabs.co.uk/journal/php-strip-attributes-class-for-xml-and-html

niggles