ord.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. /**
  3. * UTF8::ord
  4. *
  5. * @package KO7
  6. *
  7. * @copyright (c) 2007-2016 Kohana Team
  8. * @copyright (c) since 2016 Koseven Team
  9. * @copyright (c) 2005 Harry Fuecks
  10. * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt
  11. */
  12. function _ord($chr)
  13. {
  14. $ord0 = ord($chr);
  15. if ($ord0 >= 0 AND $ord0 <= 127)
  16. return $ord0;
  17. if ( ! isset($chr[1]))
  18. {
  19. throw new UTF8_Exception('Short sequence - at least 2 bytes expected, only 1 seen');
  20. }
  21. $ord1 = ord($chr[1]);
  22. if ($ord0 >= 192 AND $ord0 <= 223)
  23. return ($ord0 - 192) * 64 + ($ord1 - 128);
  24. if ( ! isset($chr[2]))
  25. {
  26. throw new UTF8_Exception('Short sequence - at least 3 bytes expected, only 2 seen');
  27. }
  28. $ord2 = ord($chr[2]);
  29. if ($ord0 >= 224 AND $ord0 <= 239)
  30. return ($ord0 - 224) * 4096 + ($ord1 - 128) * 64 + ($ord2 - 128);
  31. if ( ! isset($chr[3]))
  32. {
  33. throw new UTF8_Exception('Short sequence - at least 4 bytes expected, only 3 seen');
  34. }
  35. $ord3 = ord($chr[3]);
  36. if ($ord0 >= 240 AND $ord0 <= 247)
  37. return ($ord0 - 240) * 262144 + ($ord1 - 128) * 4096 + ($ord2-128) * 64 + ($ord3 - 128);
  38. if ( ! isset($chr[4]))
  39. {
  40. throw new UTF8_Exception('Short sequence - at least 5 bytes expected, only 4 seen');
  41. }
  42. $ord4 = ord($chr[4]);
  43. if ($ord0 >= 248 AND $ord0 <= 251)
  44. return ($ord0 - 248) * 16777216 + ($ord1-128) * 262144 + ($ord2 - 128) * 4096 + ($ord3 - 128) * 64 + ($ord4 - 128);
  45. if ( ! isset($chr[5]))
  46. {
  47. throw new UTF8_Exception('Short sequence - at least 6 bytes expected, only 5 seen');
  48. }
  49. if ($ord0 >= 252 AND $ord0 <= 253)
  50. return ($ord0 - 252) * 1073741824 + ($ord1 - 128) * 16777216 + ($ord2 - 128) * 262144 + ($ord3 - 128) * 4096 + ($ord4 - 128) * 64 + (ord($chr[5]) - 128);
  51. if ($ord0 >= 254 AND $ord0 <= 255)
  52. {
  53. throw new UTF8_Exception("Invalid UTF-8 with surrogate ordinal ':ordinal'", [
  54. ':ordinal' => $ord0,
  55. ]);
  56. }
  57. }