note 96648 added to function.htmlentities
| From: | silverbeat-eat-gmx-hot-at at osu1 dot php dot net | Date: | Tue, 09 Mar 2010 20:42:09 +0000 |
| Subject: | note 96648 added to function.htmlentities | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-166846@lists.php.net to get a copy of this message | ||
When using UTF-8 as a charset, htmlentities will only convert 1-byte and 2-byte characters. Use this
function if you also want to convert 3-byte and 4-byte characters:
<?php
// converts a UTF8-string into HTML entities
// - $utf8: the UTF8-string to convert
// - $encodeTags: booloean. TRUE will convert "<" to "<"
// - return: returns the converted HTML-string
function utf8tohtml($utf8, $encodeTags) {
$result = '';
for ($i = 0; $i < strlen($utf8); $i++) {
$char = $utf8[$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
$result .= htmlentities(substr($utf8, $i, 2), ENT_QUOTES, 'UTF-8');
$i++;
} else if ($ascii < 240) {
// three-byte character
$ascii1 = ord($utf8[$i+1]);
$ascii2 = ord($utf8[$i+2]);
$unicode = (15 & $ascii) * 4096 +
(63 & $ascii1) * 64 +
(63 & $ascii2);
$result .= "&#$unicode;";
$i += 2;
} else if ($ascii < 248) {
// four-byte character
$ascii1 = ord($utf8[$i+1]);
$ascii2 = ord($utf8[$i+2]);
$ascii3 = ord($utf8[$i+3]);
$unicode = (15 & $ascii) * 262144 +
(63 & $ascii1) * 4096 +
(63 & $ascii2) * 64 +
(63 & $ascii3);
$result .= "&#$unicode;";
$i += 3;
}
}
return $result;
}
echo utf8tohtml($anyUTF8string, TRUE);
?>
regards, silverbeat
----
Server IP: 212.124.37.9
Probable Submitter: 193.170.134.155
----
Manual Page -- http://www.php.net/manual/en/function.htmlentities.php
Edit -- https://master.php.net/note/edit/96648
Del: integrated -- https://master.php.net/note/delete/96648/integrated
Del: useless -- https://master.php.net/note/delete/96648/useless
Del: bad code -- https://master.php.net/note/delete/96648/bad+code
Del: spam -- https://master.php.net/note/delete/96648/spam
Del: non-english -- https://master.php.net/note/delete/96648/non-english
Del: in docs -- https://master.php.net/note/delete/96648/in+docs
Del: other reasons-- https://master.php.net/note/delete/96648
Reject -- https://master.php.net/note/reject/96648
Search -- https://master.php.net/manage/user-notes.php