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?
Definition and Usage. The style attribute specifies an inline style for an element. The style attribute will override any style set globally, e.g. styles specified in the <style> tag or in an external style sheet.
By setting the text-decoration to none to remove the underline from anchor tag. Syntax: text-decoration: none; Example 1: This example sets the text-decoration property to none.
The HTML tags can be removed from a given string by using replaceAll() method of String class. We can remove the HTML tags from a given string by using a regular expression. After removing the HTML tags from a string, it will return a string as normal text.
Inline Style: In this method, the style attribute is used inside the HTML start tag. Embedded Style: In this method, the style element is used inside the <head> element of the document.
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="..."
.
Something like this should work (untested code warning):
<?php $html = '<p style="asd">qwe</p><br /><p class="qwe">qweqweqwe</p>'; $domd = new DOMDocument(); libxml_use_internal_errors(true); $domd->loadHTML($html); libxml_use_internal_errors(false); $domx = new DOMXPath($domd); $items = $domx->query("//p[@style]"); foreach($items as $item) { $item->removeAttribute("style"); } echo $domd->saveHTML();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With