String Functions

PHP strip_tags() Function

Topic: PHP String ReferencePrev|Next

Description

The strip_tags() function strips the HTML and PHP tags from a string.

The following table summarizes the technical details of this function.

Return Value: Returns the stripped string.
Changelog: Since PHP 7.4.0, the allowable_tags now alternatively accepts an array.
Version: PHP 4+

Syntax

The basic syntax of the strip_tags() function is given with:

strip_tags(string, allowable_tags);

The following example shows the strip_tags() function in action.

<?php
// Sample string
$str = "<h1>Hello World!</h1>";

// Stripping HTML tags from string
echo strip_tags($str);
?>

Note: The HTML comments and PHP tags are always stripped by this function. This is hardcoded and can not be changed with the allowable_tags parameter.

Warning: This function should not be used to prevent XSS attacks. Use more appropriate functions like htmlspecialchars() or other means depending on the context.


Parameters

The strip_tags() function accepts the following parameters.

Parameter Description
string Required. Specifies the string to work on.
allowable_tags Optional. Specifies the tags which should not be stripped.

More Examples

Here're some more examples showing how strip_tags() function actually works:

Self-closing XHTML tags are ignored and only non-self-closing tags should be used in allowable_tags. For example, if you want to allow both <br> and <br/>, you should use:

<?php
// Sample string
$str = "<h1>Hello<br/>World!</h1>";

// Stripping all HTML tags except <br> and <br/>
echo strip_tags($str, "<br>");
?>

As of PHP 7.4.0, you can also pass an array as allowable_tags parameter, like this:

<?php
// Sample string
$str = '<p>Hello <b>World!<b></p><!-- Comment --><a href="#top">Top</a>';

// Stripping all HTML tags except <p> and <a>
echo strip_tags($str, ["p", "a"]);
?>
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties