1 | <?php |
---|
2 | |
---|
3 | /** |
---|
4 | * @version $Id: ord.php,v 1.4 2006/09/11 15:22:54 harryf Exp $ |
---|
5 | * @package utf8 |
---|
6 | * @subpackage strings |
---|
7 | */ |
---|
8 | |
---|
9 | /** |
---|
10 | * UTF-8 aware alternative to ord |
---|
11 | * Returns the unicode ordinal for a character |
---|
12 | * @param string UTF-8 encoded character |
---|
13 | * @return int unicode ordinal for the character |
---|
14 | * @see http://www.php.net/ord |
---|
15 | * @see http://www.php.net/manual/en/function.ord.php#46267 |
---|
16 | */ |
---|
17 | function utf8_ord($chr) |
---|
18 | { |
---|
19 | $ord0 = ord($chr); |
---|
20 | |
---|
21 | if ($ord0 >= 0 && $ord0 <= 127) |
---|
22 | return $ord0; |
---|
23 | |
---|
24 | if (!isset($chr{1})) |
---|
25 | { |
---|
26 | trigger_error('Short sequence - at least 2 bytes expected, only 1 seen'); |
---|
27 | return false; |
---|
28 | } |
---|
29 | |
---|
30 | $ord1 = ord($chr{1}); |
---|
31 | if ($ord0 >= 192 && $ord0 <= 223) |
---|
32 | return ($ord0 - 192) * 64 + ($ord1 - 128); |
---|
33 | |
---|
34 | if (!isset($chr{2})) |
---|
35 | { |
---|
36 | trigger_error('Short sequence - at least 3 bytes expected, only 2 seen'); |
---|
37 | return false; |
---|
38 | } |
---|
39 | |
---|
40 | $ord2 = ord($chr{2}); |
---|
41 | if ($ord0 >= 224 && $ord0 <= 239) |
---|
42 | return ($ord0-224)*4096 + ($ord1-128)*64 + ($ord2-128); |
---|
43 | |
---|
44 | if (!isset($chr{3})) |
---|
45 | { |
---|
46 | trigger_error('Short sequence - at least 4 bytes expected, only 3 seen'); |
---|
47 | return false; |
---|
48 | } |
---|
49 | |
---|
50 | $ord3 = ord($chr{3}); |
---|
51 | if ($ord0>=240 && $ord0<=247) |
---|
52 | return ($ord0-240)*262144 + ($ord1-128)*4096 + ($ord2-128)*64 + ($ord3-128); |
---|
53 | |
---|
54 | if (!isset($chr{4})) |
---|
55 | { |
---|
56 | trigger_error('Short sequence - at least 5 bytes expected, only 4 seen'); |
---|
57 | return false; |
---|
58 | } |
---|
59 | |
---|
60 | $ord4 = ord($chr{4}); |
---|
61 | if ($ord0>=248 && $ord0<=251) |
---|
62 | return ($ord0-248)*16777216 + ($ord1-128)*262144 + ($ord2-128)*4096 + ($ord3-128)*64 + ($ord4-128); |
---|
63 | |
---|
64 | if (!isset($chr{5})) |
---|
65 | { |
---|
66 | trigger_error('Short sequence - at least 6 bytes expected, only 5 seen'); |
---|
67 | return false; |
---|
68 | } |
---|
69 | |
---|
70 | if ($ord0>=252 && $ord0<=253) |
---|
71 | return ($ord0-252) * 1073741824 + ($ord1-128)*16777216 + ($ord2-128)*262144 + ($ord3-128)*4096 + ($ord4-128)*64 + (ord($c{5})-128); |
---|
72 | |
---|
73 | if ($ord0 >= 254 && $ord0 <= 255) |
---|
74 | { |
---|
75 | trigger_error('Invalid UTF-8 with surrogate ordinal '.$ord0); |
---|
76 | return false; |
---|
77 | } |
---|
78 | } |
---|