note 77905 deleted from function.ord by danbrown
| From: | danbrown@php.net | Date: | Tue, 11 Oct 2011 16:06:55 +0000 |
| Subject: | note 77905 deleted from function.ord by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-183797@lists.php.net to get a copy of this message | ||
Note Submitter: Miguel Perez
----
The following uniord function is simpler and more efficient than any of the ones suggested without
depending on mbstring or iconv. It's also more validating (code points above U+10FFFF are
invalid; sequences starting with 0xC0 and 0xC1 are invalid overlong encodings of characters below
U+0080), though not entirely validating, so it still assumes proper input.
<?php
function uniord($c) {
$h = ord($c{0});
if ($h <= 0x7F) {
return $h;
} else if ($h < 0xC2) {
return false;
} else if ($h <= 0xDF) {
return ($h & 0x1F) << 6 | (ord($c{1}) & 0x3F);
} else if ($h <= 0xEF) {
return ($h & 0x0F) << 12 | (ord($c{1}) & 0x3F) << 6
| (ord($c{2}) & 0x3F);
} else if ($h <= 0xF4) {
return ($h & 0x0F) << 18 | (ord($c{1}) & 0x3F) << 12
| (ord($c{2}) & 0x3F) << 6
| (ord($c{3}) & 0x3F);
} else {
return false;
}
}
?>
If you want a fully validating function, you'll need to check the extra octets are between 0x80
and 0xBF, and there are no overlong encodings (characters below a certain point in n-octet
sequences).