How do I strip HTML tags from text?

chinmay.sahoo

New member
If you allow your site to be updated by the general public, it’s important to prevent the use of HTML—you want to prevent visitors from posting markup that interferes with your site’s layout.

Solution
The PHP function strip_tags handles this job almost perfectly. Given some text, strip_tags will eliminate anything that looks like an HTML tag. To be more exact, strip_tags removes any block of text that begins with < and ends with >, while everything other than the tags is left exactly as it was. Here’s a simple example:

<?php
$text = 'This is <b>bold</b> and this is <i>italic</i>. What about
➥ this <a href="http://www.php.net/">link</a>?';
echo strip_tags($text);
?>

This results in the following output:

You can also supply strip_tagswith a list of allowed tags that you want it to ignore. Let’s alter the above example slightly:

echo strip_tags($text, '<b><i>');

This time, strip_tags will ignore the <b> and <i> tags and strip the rest, producing the following output
This is <b>bold</b> and this is <i>italic</i>. What about this link?
This is bold and this is italic. What about this link?
 
Back
Top