String Functions
Advertisements

PHP htmlspecialchars_decode() Function

Topic: PHP String ReferencePrev|Next

Description

The htmlspecialchars_decode() function converts special HTML entities back to their corresponding characters. The special HTML entities are:

  • & converted to & (ampersand)
  • " converted to " (double quote), when ENT_NOQUOTES is not set.
  • ' converted to ' (single quote), when ENT_QUOTES is set.
  • &lt; converted to < (less than)
  • &gt; converted to > (greater than)

This function typically reverses the effect of htmlspecialchars() function.

The following table summarizes the technical details of this function.

Return Value: Returns the decoded string.
Version: PHP 5.1.0+

Syntax

The basic syntax of the htmlspecialchars_decode() function is given with:

htmlspecialchars_decode(string, flags);

The following example shows the htmlspecialchars_decode() function in action.

<?php
// Sample string
$str = "The lions & tigers live in <b>dense</b> forest.";

// Encoding the string
$encoded_str = htmlspecialchars($str);
echo $encoded_str . "<br>";

// Decoding the string
$decoded_str = htmlspecialchars_decode($encoded_str);
echo $decoded_str;
?>

Parameters

The htmlspecialchars_decode() function accepts the following parameters.

Parameter Description
string Required. Specifies the string to decode.
flags

Optional. Specifies how to handle quotes and which document type to use.

The available flags constants for handling quotes are:

  • ENT_COMPAT – Converts double-quotes and leave single-quotes unconverted.
  • ENT_QUOTES – Convert both double and single quotes.
  • ENT_NOQUOTES – Leave both double and single quotes unconverted.

The available flags constants for specifying the document types are:

  • ENT_HTML401 – Handle code as HTML 4.01.
  • ENT_HTML5 – Handle code as HTML 5.
  • ENT_XML1 – Handle code as XML 1.
  • ENT_XHTML – Handle code as XHTML.

The default value for this parameter is ENT_COMPAT | ENT_HTML401.


More Examples

Here're some more examples showing how htmlspecialchars_decode() function actually works:

The following example demonstrates the handling of single and double quotes using this function.

<?php
// Sample string
$str = "I'll \"leave\" tomorrow.";

// Encoding the string
$encoded_str = htmlspecialchars($str, ENT_QUOTES);
echo $encoded_str; /* I&#039;ll &quot;leave&quot; tomorrow. */

// Decodes only double-quotes
$a = htmlspecialchars_decode($encoded_str);
echo $a; /* I&#039;ll "leave" tomorrow. */

// Decodes both double and single quotes
$b = htmlspecialchars_decode($encoded_str, ENT_QUOTES);
echo $b; /* I'll "leave" tomorrow. */
?>

However, in the browser you will always see the string I'll "leave" tomorrow. View source (right-click and select View Page Source) of the example output to see the converted string.

Advertisements
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties