If you are building an application where you allow your users to input content through and HTML editor, often they will simply copy and paste from Word or other applications that might add some weird tags which might endup breaking your layout or causing the content not to display as expected.
One solution is to clean the content prior to displaying it or prior to posting it into the database. Eitherway, the resulting content will display with only the chosen HTML tags, thus giving you more control on the final display to your visitors and removing all junk code that nobody wants and that could cause display headaches for you.
<?php $sampletext = '<b>Some bold content</b> <a href="">Test</a><h3>some more text</h3><p>More content here</p>'; echo strip_tags($sampletext); //The above code usses the built in PHP function strip_tags, which will remove/strip all tags. echo strip_tags($sampletext, '<p><a><h3>'); //The above code uses the same built in PHP strip_tags function, but we added some exceptions to it. Any tag listed as an exception will not be removed/striped. ?>
As you can see it is pretty easy to control what tags get stripped and which ones do not.
You can also apply the same strip_tags function prior to posting to a MySQL database, so that the content will be saved only with the enabled tags you allow or no tags if you did not specify any exceptions.
No matter if you use the function prior to posting to your database or after, it will save many headaches and you will retain control of the display of the content on the site and prevent other script from breaking due to junk code.
Leave a comment