Removing HTML from a PHP string
- Posted by - Ahtasham Khan
- On -
string strip_tags ( string source [, string allowable_tags])
Strip_tags() is a function that allows you to strip out all HTML and PHP tags from a given string (parameter one), however you can also use parameter two to specify a list of HTML tags you want.
This function can be very helpful if you ever display user input on your site. For example, if you create your own message board forum on your site a user could post a title along the lines of: <h1>THIS SITE SUCKS!</h1>, which, because you would display the titles of each post on your board, would display their unwanted message in huge letters on your visitors’ screens.
Here are two examples of stripping out tags:
<?php $input = "<blink><strong>Hello!</strong></blink>"; $a = strip_tags($input); $b = strip_tags($input, "<strong><em>"); ?>
After running that script, $a will be set to “Hello!”, whereas $b will be set to “<strong>Hello!</strong>” because we had “<strong>” in the list of acceptable tags. Using this method you can eliminate most users from adversely changing the style of your site, however it is still possible for users to cause trouble if you allow a list of certain HTML tags, for example, we could abuse the allow <strong> tag using CSS: <strong style=”font: 72pt Times New Roman”>THIS SITE SUCKS!</strong>.
If you allow <strong> tags, you allow all <strong> tags, regardless of whether they have any extra unwanted information in there, so it is best not to allow any tags.