note 109812 added to function.ord
| From: | arglanir+phpnet at gmail dot com | Date: | Thu, 23 Aug 2012 15:06:10 +0000 |
| Subject: | note 109812 added to function.ord | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-190194@lists.php.net to get a copy of this message | ||
As ord() doesn't work with utf-8, and if you do not have access to mb_* functions, the
following function will work well:
<?php
function ordutf8($string, &$offset) {
$code = ord(substr($string, $offset,1));
if ($code >= 128) { //otherwise 0xxxxxxx
if ($code < 224) $bytesnumber = 2; //110xxxxx
else if ($code < 240) $bytesnumber = 3; //1110xxxx
else if ($code < 248) $bytesnumber = 4; //11110xxx
$codetemp = $code - 192 - ($bytesnumber > 2 ? 32 : 0) - ($bytesnumber > 3 ? 16 : 0);
for ($i = 2; $i <= $bytesnumber; $i++) {
$offset ++;
$code2 = ord(substr($string, $offset, 1)) - 128; //10xxxxxx
$codetemp = $codetemp*64 + $code2;
}
$code = $codetemp;
}
$offset += 1;
if ($offset >= strlen($string)) $offset = -1;
return $code;
}
?>
$offset is a reference, as it is not easy to split a utf-8 char-by-char. Useful to iterate on a
string:
<?php
$text = "abcà êÃâ¬abc";
$offset = 0;
while ($offset >= 0) {
echo $offset.": ".ordutf8($text, $offset)."\n";
}
/* returns:
0: 97
1: 98
2: 99
3: 224
5: 234
7: 223
9: 8364
12: 97
13: 98
14: 99
*/
?>
Feel free to adapt my code to fit your needs.
----
Server IP: 91.199.167.223
Probable Submitter: 192.54.144.229
----
Manual Page -- http://www.php.net/manual/en/function.ord.php
Edit -- https://master.php.net/note/edit/109812
Del: integrated -- https://master.php.net/note/delete/109812/integrated
Del: useless -- https://master.php.net/note/delete/109812/useless
Del: bad code -- https://master.php.net/note/delete/109812/bad+code
Del: spam -- https://master.php.net/note/delete/109812/spam
Del: non-english -- https://master.php.net/note/delete/109812/non-english
Del: in docs -- https://master.php.net/note/delete/109812/in+docs
Del: other reasons-- https://master.php.net/note/delete/109812
Reject -- https://master.php.net/note/reject/109812
Search -- https://master.php.net/manage/user-notes.php