How to Remove HTML tags from String in PHP - strip_tags() Function

PHP String Functions

The strip_tags() function removes or strips HTML and PHP tags from a given string. It removes all HTML and PHP tags, leaving only the plain text content.

This can be useful when you want to prevent users from injecting HTML or script tags into input fields to protect against potential security vulnerabilities such as cross-site scripting (XSS).

Syntax

strip_tags($string, $allowed_tags = null)

Parameters

  • $string: The input string.
  • $allowed_tags: Optional parameter to specify tags which should not be stripped. These are either given as string, or as array.

HTML comments and PHP tags are also stripped. This can not be changed with allowed_tags.

Example

$html = "<p>This is <b>bold</b> text.</p><a href='#'>Link</a>";
$plain_text = strip_tags($html);
echo $plain_text;

Output: This is bold text. Link