PHP – Convert Special Characters to HTML Entities

I was working on a legacy CMS which has a HTML form with ISO-8859-1 encoding. I found that whenever i got an Apostrophe (‘) in the string, the data cannot be persisted.

I guess it should be some encoding problem which makes the database fail to persist the data. So i try to use the PHP str_replace function to replace those Apostrophe but it has never replaced them successfully.

Finally, i got the solution. PHP provide a function called htmlspecialchars which will substitute the following special characters into HTML entities.

  • Ampersand & becomes &
  • Double Quote ” becomes " when ENT_NOQUOTES is not set
  • Singe Quote/Apostrophe ‘ becomes ' only when ENT_QUOTES is set
  • Less Than < becomes &lt;
  • More Than > becomes &gt;

 

Example:

$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;

 

If you want to convert all other special characters into HTML entities. You could try the htmlentities function.

Done =)

Reference:

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.