Ignore or strip HTML tags from strings in PHP

This tutorial explains how to use the htmlentities and strip_tags functions in PHP to ignore or strip HTML tags in strings. You may want to do this if you are allowing users to enter data into a form element such as a text box and don’t want the user to be able to mess up the display of your website by adding HTML tags to data.

The first function called htmlentities, is used to ignore HTML tags in strings. The second function called strip_tags is used to completely remove the HTML tags from a string. Watch the video below to see how you can protect your website or web app using these functions with forms and then scroll down to see the sample code.

Sample PHP code:

<!DOCTYPE html>
<html>
<head>
  <title>HTML entities and strip tags</title>
</head>

<body>
  <?php
    if(isset($_GET['string1'])){
      echo "Using htmlentities function: " , htmlentities($_GET['string2']), "<br/>";
      // htmlentities displays HTML tags as they are
    }

    if(isset($_GET['string2'])){
      echo "Using strip_tags function: " , strip_tags($_GET['string2']), "<br/>";
      // strip_tags will strip the HTML tags
    }
  ?>
  <h3>Enter your name below:</h3>
  <form action="" method="GET">
    First string (using htmlentities): <input type="text" name="string1"><br/>
    Second string (using strip_tags): <input type="text" name="string2"><br/>
    <input type="submit">
  </form>
</body>
</html>