PHP htmlentities() Function

PHP htmlentities() Function converts some characters to HTML entities. Function htmlentities() is php in built function.

Syntax :

htmlentities(string,flags,character-set,double_encode);  

Parameter,

PHP htmlentities() Function
Parameter Description
string Required. It is input string.
flags

Optional. It specifies how to handle quotes, invalid encoding and the used document type.The default is ENT_COMPAT | ENT_HTML401.
Flags for quotes are as below,

  1. ENT_COMPAT - Encodes only double quotes
  2. ENT_QUOTES - Encodes double and single quotes
  3. ENT_NOQUOTES - Does not encode any quotes

Flags for invalid encoding are as below,

  1. ENT_IGNORE  - It ignores invalid encoding
  2. ENT_SUBSTITUTE  - It replaces invalid code unit sequences with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD;
  3. ENT_DISALLOWED  - It replaces code points that are invalid in the specified doctype with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD;

Flags for used doctype as below,

  1. ENT_HTML401 - Default. It handles code as HTML 4.01
  2. ENT_HTML5 - It handles code as HTML 5
  3. ENT_XML1 - It handles code as XML 1
  4. ENT_XHTML - It handles code as XHTML
character-set

Optional. It specifies which character-set to use for string.

Allowed character-set are as below.

  1. UTF-8
  2. ISO-8859-1
  3. ISO-8859-15
  4. GB2312
  5. cp1251
  6. cp1252
double_encode

Optional.A boolean value that specifies whether to encode existing html entities or not.

  1. TRUE - Default. It Will convert everything.
  2. FALSE - It Will not encode existing html entities.

Let's see below example to understand php htmlentities() Function in details.

HTML Output for below example in view source as below,

<br>Maths &lt;b&gt;equation&lt;/b&gt; =&gt; '(a+b)*c' ='ac+bc'<br>
Using ENT_COMPAT flag :Maths &lt;b&gt;equation&lt;/b&gt; =&gt; '(a+b)*c' ='ac+bc'<br>
Using ENT_QUOTES flag :Maths &lt;b&gt;equation&lt;/b&gt; =&gt; &#039;(a+b)*c&#039; =&#039;ac+bc&#039;<br>
Using ENT_NOQUOTES flag :Maths &lt;b&gt;equation&lt;/b&gt; =&gt; '(a+b)*c' ='ac+bc'
Using UTF-8 character-set : Maths &lt;b&gt;equation&lt;/b&gt; =&gt; &#039;(a+b)*c&#039; =&#039;ac+bc&#039;

Example :

<br><b>The browser output of the above code as below.</b>
<?php
$str = "Maths <b>equation</b> => '(a+b)*c' ='ac+bc'";
echo "<br>".htmlentities($str); // It will convert characters to HTML entities.
echo "<br>Using ENT_COMPAT flag :".htmlentities($str, ENT_COMPAT); // It will only convert double quotes.
echo "<br>Using ENT_QUOTES flag :".htmlentities($str, ENT_QUOTES); // It will convert double and single quotes .
echo "<br>Using ENT_NOQUOTES flag :".htmlentities($str, ENT_NOQUOTES); // It will not convert any quotes.
echo "<br> Using UTF-8 character-set : ".htmlentities($str, ENT_QUOTES | ENT_IGNORE, "UTF-8");
?>

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

19290