How to remove HTML special characters from a string in PHP

Topic: PHP / MySQL« Prev|Next »

Answer: Use the PHP htmlspecialchars() function

Certain characters such as (&, ", ', <, >) have special significance in HTML, and should be converted to HTML entities. You can use the PHP htmlspecialchars() function to convert special characters in a string to HTML entities. Here's is an example.

  • <?php
  • $my_str = "String with <b>special</b> characters.";
  • // Removing HTML special characters
  • echo htmlspecialchars($my_str);
  • ?>

If you view the source code of the output you will the string "String with <b>special</b> characters." converted to "String with &lt;b&gt;special&lt;/b&gt; characters."

Related FAQ

Here are some more FAQ related to this topic:


Your Feedback:


We would love to hear from you! Please say something.