Name

strip_tags()

Synopsis

    string strip_tags ( string html_text [, string allowed_tags] )

You can strip HTML and PHP tags from a string using strip_tags(). Parameter one is the string you want stripped, and parameter two lets you specify a list of HTML tags you want to keep.

This function can be very helpful if you 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:

    $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>, a situation shown in Figure 7-1.

Not what you want to see—strip_tags() gone wrong

Figure 7-1. Not what you want to see—strip_tags() gone wrong

If you allow <strong> ...

Get PHP in a Nutshell 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.