How to remove attributes from within a tag using regular expression in PHP

If you have come across a situation where the content in your database is using different style attributes from what is required on your website then this post is for you.

Most websites use some sort of RTE’s like CKEditor, TinyMCE etc for providing an interface to add/change style on the content. Now this is all fine if the person adding them is skilled in HTML/CSS and he can make changes to the style of the content but if that is not so then you may end up with a problem with the content not giving a uniform look with respect to the rest of the content on the website. Your website may look unprofessional due to this.

However there is a way out of this using regular expressions. You can resolve this issue using the following code:

Some Link';
$strNewVal = preg_replace('/(<[^>]+) style=".*?"|class=".*?"/i', '$1', $strVal);

// This will print Some Link

echo $strNewVal;

The original solution was here. I have made the changes to the code for the class attribute.

I hope the above helped you.

Be the first to comment

Leave a Reply