from_unicode.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. /**
  3. * UTF8::from_unicode
  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 _from_unicode($arr)
  13. {
  14. ob_start();
  15. $keys = array_keys($arr);
  16. foreach ($keys as $k)
  17. {
  18. // ASCII range (including control chars)
  19. if (($arr[$k] >= 0) AND ($arr[$k] <= 0x007f))
  20. {
  21. echo chr($arr[$k]);
  22. }
  23. // 2 byte sequence
  24. elseif ($arr[$k] <= 0x07ff)
  25. {
  26. echo chr(0xc0 | ($arr[$k] >> 6));
  27. echo chr(0x80 | ($arr[$k] & 0x003f));
  28. }
  29. // Byte order mark (skip)
  30. elseif ($arr[$k] == 0xFEFF)
  31. {
  32. // nop -- zap the BOM
  33. }
  34. // Test for illegal surrogates
  35. elseif ($arr[$k] >= 0xD800 AND $arr[$k] <= 0xDFFF)
  36. {
  37. // Found a surrogate
  38. throw new UTF8_Exception("UTF8::from_unicode: Illegal surrogate at index: ':index', value: ':value'", [
  39. ':index' => $k,
  40. ':value' => $arr[$k],
  41. ]);
  42. }
  43. // 3 byte sequence
  44. elseif ($arr[$k] <= 0xffff)
  45. {
  46. echo chr(0xe0 | ($arr[$k] >> 12));
  47. echo chr(0x80 | (($arr[$k] >> 6) & 0x003f));
  48. echo chr(0x80 | ($arr[$k] & 0x003f));
  49. }
  50. // 4 byte sequence
  51. elseif ($arr[$k] <= 0x10ffff)
  52. {
  53. echo chr(0xf0 | ($arr[$k] >> 18));
  54. echo chr(0x80 | (($arr[$k] >> 12) & 0x3f));
  55. echo chr(0x80 | (($arr[$k] >> 6) & 0x3f));
  56. echo chr(0x80 | ($arr[$k] & 0x3f));
  57. }
  58. // Out of range
  59. else
  60. {
  61. throw new UTF8_Exception("UTF8::from_unicode: Codepoint out of Unicode range at index: ':index', value: ':value'", [
  62. ':index' => $k,
  63. ':value' => $arr[$k],
  64. ]);
  65. }
  66. }
  67. $result = ob_get_contents();
  68. ob_end_clean();
  69. return $result;
  70. }