Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove style attribute from HTML tags

Tags:

regex

php

tinymce

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?

like image 230
Martin Bean Avatar asked Apr 01 '11 18:04

Martin Bean


People also ask

What is style attribute in HTML?

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.

How do you remove a tag in CSS?

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.

How do I remove text tags in HTML?

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.

Where can we find the style attribute?

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.


2 Answers

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="...".

like image 93
Staffan Nöteberg Avatar answered Sep 27 '22 19:09

Staffan Nöteberg


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(); 
like image 28
Maerlyn Avatar answered Sep 27 '22 21:09

Maerlyn