note 97486 added to function.htmlentities
| From: | tal at talater dot com | Date: | Thu, 22 Apr 2010 12:37:17 +0000 |
| Subject: | note 97486 added to function.htmlentities | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-168503@lists.php.net to get a copy of this message | ||
We've adapted the excellent function provided by silverbeat, so that it also encodes two-byte
characters. This made it safer for the output to be used in XML (which previously choked on output
like £ which the original function put out).
/**
* Encodes a string for use in XML
*
* @param string $string
* @param boolean $encodeTags=true
* @return string
*/
function xml_character_encode($string, $encodeTags=true) {
$string = html_entity_decode($string, ENT_COMPAT, 'UTF-8');
$result = '';
for ($i = 0; $i < strlen($string); $i++) {
$char = $string[$i];
$ascii = ord($char);
if ($ascii < 128) {
// one-byte character
$result .= ($encodeTags) ? htmlentities($char) : $char;
} else if ($ascii < 192) {
// non-utf8 character or not a start byte
} else if ($ascii < 224) {
// two-byte character
$ascii1 = ord($string[$i+1]);
$unicode = (63 & $ascii) * 64 +
(63 & $ascii1);
$result .= "&#$unicode;";
$i++;
} else if ($ascii < 240) {
// three-byte character
$ascii1 = ord($string[$i+1]);
$ascii2 = ord($string[$i+2]);
$unicode = (15 & $ascii) * 4096 +
(63 & $ascii1) * 64 +
(63 & $ascii2);
$result .= "&#$unicode;";
$i += 2;
} else if ($ascii < 248) {
// four-byte character
$ascii1 = ord($string[$i+1]);
$ascii2 = ord($string[$i+2]);
$ascii3 = ord($string[$i+3]);
$unicode = (15 & $ascii) * 262144 +
(63 & $ascii1) * 4096 +
(63 & $ascii2) * 64 +
(63 & $ascii3);
$result .= "&#$unicode;";
$i += 3;
}
}
return $result;
}
----
Server IP: 69.147.83.197
Probable Submitter: 69.46.25.228
----
Manual Page -- http://www.php.net/manual/en/function.htmlentities.php
Edit -- https://master.php.net/note/edit/97486
Del: integrated -- https://master.php.net/note/delete/97486/integrated
Del: useless -- https://master.php.net/note/delete/97486/useless
Del: bad code -- https://master.php.net/note/delete/97486/bad+code
Del: spam -- https://master.php.net/note/delete/97486/spam
Del: non-english -- https://master.php.net/note/delete/97486/non-english
Del: in docs -- https://master.php.net/note/delete/97486/in+docs
Del: other reasons-- https://master.php.net/note/delete/97486
Reject -- https://master.php.net/note/reject/97486
Search -- https://master.php.net/manage/user-notes.php