IT & Programming

Removing style attribute from a string with PHP

Sometime you need to remove style attribute from an html element. Below function is designed to perform this task.

Function

function stripStyle($string) {
    
    return preg_replace('/(<[^>]+) style=".*?"/i', '$1', $string);     
}

Calling The Function

$string = '< div style="font-size:10px;color:red">Hello World!< /div>';

echo stripStyle($string);

Output

< div>Hello World!< /div>

Comments

  1. Robust Group Albuquerque February 02, 2019

    Nice try but this is not a style tag- it is a style attribute. so people looking for this solution gets something else. the right solution is here: https://stackoverflow.com/questions/18089173/how-to-use-preg-replace-to-remove-all-following-style-tag-pattern-occurrences-in

Leave A comment

Email address is optional and will not be published. Only add email address if you want a reply from blog author.
Please fill required fields marked with *