PHP strip_tags Function | Remove HTML Tags from String

PHP strip_tags is an inbuilt function in PHP. It removes all HTML, PHP tags and NULL bytes from a string after processing. It returns the same string after removing HTML and PHP tags. In this article, we will discuss the PHP strip_tags Function. Also, we will discuss a few examples of using it.

Note: You should not use this function to prevent XSS attacks. However, you can use htmlspecialchars or any other function depending on the context.


string strip_tags( $string, $allowable_tags )


The PHP strip_tags function expects two parameters. However, one parameter is mandatory and the other is optional.

  • $string: The input string is the first parameter. Also, it is a mandatory parameter.
  • $allowable_tags: The second parameter specifies a list of tags to not remove from the string. Also, it is an optional parameter.

Note: The function will always strip HTML Comments and PHP tags as they are hardcoded. Also, you cannot change this behavior by allowable_tags parameter.

Return Value

The PHP strip_tags function returns a string after removing HTML and PHP tags along with the Null bytes from the string.

Note: The function does not validate the HTML. Therefore, partial or invalid tags may result in the removal of more data than expected.

PHP strip_tags Function


Let’s discuss a few examples of using the function.

Example 1: Removing All Tags

For instance, consider the example for removing all the tags from the input string.

	$htmlString = '<p>Test paragraph.</p><!-- Comment --> <a href="#partA">Part A</a>';

	$strippedString = strip_tags($htmlString);
	echo $strippedString;


In the above example, the function removes the paragraph (p), anchor (a) and HTML comments from the string. The output is as follows:

Test paragraph. Part A

Example 2: Allowing Some Tags

Alternatively, you can allow some tags using the second parameter. The function will not remove these tags from the string.

	$htmlString = '<p>Test paragraph.</p><!-- Comment --> <a href="#partA">Part A</a>';

	$strippedString = strip_tags($htmlString, '<a><p>');
	echo $strippedString;


In the above example, we allow the paragraph (p) and anchor (a) tag by passing them in the second parameter. The strip_tags function in PHP strips all the remaining tags from the list.

<p>Test paragraph.</p> <a href="#partA">Part A</a>


In conclusion, we discussed the PHP strip_tags Function in this article. You can read more about it on the PHP Official Documentation. Additionally, you can learn more about PHP String Functions on Concatly.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *