note 61205 deleted from function.html-entity-decode by nlopess
| From: | nlopess@php.net | Date: | Sat, 28 Jan 2006 10:55:19 +0000 |
| Subject: | note 61205 deleted from function.html-entity-decode by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-102606@lists.php.net to get a copy of this message | ||
Note Submitter: timburgan <at> gmail <dot> com
----
To decode characters within a string that have been encoded to their HTML character code (in the
format &#xx;), use the following function unicode_decode().
A list of HTML character codes can be found at: http://www.ascii.cl/htmlcodes.htm
Note: To encode a string to HTML character codes (in the format &#xx;), use the function
unicode_entities(), listed in the comments of http://php.net/manual/function.htmlentities.php
<?php
/**
* Decode each char in a string from its HTML code.
* Characters denoded by this function were encoded
* by unicode_entities().
*
* This function will work with PHP >= 3.0.9, 4, 5.
*
* @author Tim Burgan <timburgan@gmail.com>
* @version 1.0.0
* @link http://timburgan.com/
* @link http://php.net/manual/function.html-entity-decode.php
* @see http://php.net/manual/function.htmlentities.php
* @param string $string String to decode
* @return string Returns a string of decoded chars
*/
function unicode_decode($string)
{
// declare variables
$tok = 0;
$cur = 0;
$chars = null;
// move through the string until the end is reached
while ( $cur < strlen($string) )
{
// find the next token
$tok = strpos($string, "&#", $cur);
// if no more tokens exist, move pointer to end of string
if ( $tok === false )
$tok = strlen($string);
// if the current char is alpha-numeric or a space
if ( preg_match("/^(w| )$/",substr($string, $cur, 1)) )
{
$chars .= substr($string, $cur, $tok - $cur);
}
// the current char must be the start of a token
else
{
$cur += 2;
$tok = strpos($string, ';', $cur);
$chars .= chr(substr($string, $cur, $tok - $cur));
$tok++;
}
// move the current pointer to the next token
$cur = $tok;
}
return $chars;
}
?>
Usage:
<?php
$string = "<a
href="http://timburgan.com"
rel="external" title="Go to
timburgan.com">Tim Burgan</a>";
echo unicode_decode($string);
?>
Output:
<a href="http://timburgan.com"
rel="external" title="Go to timburgan.com">Tim Burgan</a>