Open In App

How to remove HTML tags from data in PHP ?

Last Updated : 16 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Removing HTML tags from data in PHP is a crucial step for sanitizing user input or displaying content safely. This process involves using the strip_tags() function to eliminate any HTML or PHP tags from a string, leaving only plain text. It’s essential for preventing potential security risks, such as cross-site scripting (XSS) attacks, and ensuring that the content is clean and displayed correctly in different contexts.

Syntax:

strip_tags(string, allowed_tags)

Parameters Values:

  • string: It is a required parameter that specifies the string to check.
  • allowed_tags: It is an optional parameter that specifies the allowable tags that will not be removed from the returned result.

Return Value: It returns a string where HTML tags are removed except for the allowed tags.

Example 1: In this example, we use strip_tags() to remove HTML tags from the string, outputting only the plain text: “GeeksforGeeks one of the popular online learning site”.

PHP
<?php
    
    echo strip_tags(
    "<b>GeeksforGeeks</b> one of the popular
    <i>online learning site</i>");

?>

Output:

Example 2: The strip_tags() function, with the allowed_tags parameter set to <h1>, preserves <h1> tags while removing others, like <i>, from the input string.

PHP
<?php
    
    echo strip_tags(
    "<h1>GeeksforGeeks</h1> one of the top
    <i>Online learning platform</i>","
    <h1>");

?>

Output:



Next Article

Similar Reads