note 45561 modified in function.utf8-decode by aidan
| From: | aidan@php.net | Date: | Sat, 11 Sep 2004 07:38:17 +0000 |
| Subject: | note 45561 modified in function.utf8-decode by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-76443@lists.php.net to get a copy of this message | ||
big thanks to wielspm and mittag for the function to convert wide utf to html. I have altered your
function to output decimal html entities which i hear are more widely supported. Also I've
optimized it, it is now twice as fast.
<?php
function utf2html ($str) {
$ret = "";
$max = strlen($str);
$last = 0; // keeps the index of the last regular character
for ($i=0; $i<$max; $i++) {
$c = $str{$i};
$c1 = ord($c);
if ($c1>>5 == 6) { // 110x xxxx, 110 prefix for 2 bytes unicode
$ret .= substr($str, $last, $i-$last); // append all the regular characters we've passed
$c1 &= 31; // remove the 3 bit two bytes prefix
$c2 = ord($str{++$i}); // the next byte
$c2 &= 63; // remove the 2 bit trailing byte prefix
$c2 |= (($c1 & 3) << 6); // last 2 bits of c1 become first 2 of c2
$c1 >>= 2; // c1 shifts 2 to the right
$ret .= "&#" . ($c1 * 100 + $c2) . ";"; // this is the fastest string
concatenation
$last = $i+1;
}
}
return $ret . substr($str, $last, $i); // append the last batch of regular characters
}
?>
--was--
big thanks to wielspm and mittag for the function to convert wide utf to html. I have altered your
function to output decimal html entities which i hear are more widely supported. Also I've
optimized it, it is now twice as fast.
function utf2html ($str) {
$ret = "";
$max = strlen($str);
$last = 0; // keeps the index of the last regular character
for ($i=0; $i<$max; $i++) {
$c = $str{$i};
$c1 = ord($c);
if ($c1>>5 == 6) { // 110x xxxx, 110 prefix for 2 bytes unicode
$ret .= substr($str, $last, $i-$last); // append all the regular characters we've
passed
$c1 &= 31; // remove the 3 bit two bytes prefix
$c2 = ord($str{++$i}); // the next byte
$c2 &= 63; // remove the 2 bit trailing byte prefix
$c2 |= (($c1 & 3) << 6); // last 2 bits of c1 become first 2 of c2
$c1 >>= 2; // c1 shifts 2 to the right
$ret .= "&#" . ($c1 * 100 + $c2) . ";"; // this is the fastest
string concatenation
$last = $i+1;
}
}
return $ret . substr($str, $last, $i); // append the last batch of regular characters
}
http://php.net/manual/en/function.utf8-decode.php