Strip HTML Tags in PHP

Quickly remove HTML tags from a string using PHP with the following code snippet.

Usage

To strip HTML tags in PHP, you can use the strip_tags function. This function removes all HTML and PHP tags from a given string, leaving only the plain text.

PHP
// Your input string with HTML tags
$inputString = "<p>This is <b>HTML</b> content.</p>";

// Strip HTML tags
$strippedString = strip_tags($inputString);

// Output the result
echo $strippedString;

In this example, the $inputString contains HTML tags, and the strip_tags function is applied to remove them. The result, stored in $strippedString, will be the plain text without any HTML tags.

Allow specify tags

You can allow specific HTML tags while stripping all others by providing a list of allowed tags as the second parameter to the strip_tags function:

PHP
$allowedTags = '<p><a>';
$strippedString = strip_tags($inputString, $allowedTags);

Remove Only Specified Tags

To remove specific HTML tags while keeping all others, you can use preg_replace with a regular expression:

PHP
// Remove <b> tags
$removedTags = ['<b>', '</b>'];
$strippedString = preg_replace('/' . implode('|', array_map('preg_quote', $removedTags)) . '/', '', $inputString);

In this example, the <b> tags will be removed from the input string. Adjust the $removedTags array to include the tags you want to remove.

FAQs

Does strip_tags remove attributes within tags?

By default, strip_tags removes both tags and their attributes. If you want to keep certain attributes, you may need to use a different approach, such as a custom function or a library.

References

  1. PHP Manual – strip_tags
  2. PHP Manual – preg_replace

Leave a Reply