#44: Stripping HTML Tags from Strings

Regular expressions are useful, but they're not the solution to every problem. Let's say that you plan to display possibly HTML-rich text inside another HTML page, and you need to strip out any possibly harmful HTML. Use the strip_tags() function:

<?php
print strip_tags($string);
?>

To add a few tags that you think users should be able to use, add an extra string parameter containing the open tags that you want to permit:

print strip_tags($string, "<i><b><p>");

This function is just one of many text-processing functions that PHP offers as an alternative to regular expressions or other do-it-yourself solutions. It's always worth a trip to the PHP manual to see if there's a built-in for your needs. But don't be ...

Get Wicked Cool PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.