utf_8.php 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. /**
  3. * utf-8 encoding function
  4. *
  5. * takes a string of unicode entities and converts it to a utf-8 encoded string
  6. * each unicode entitiy has the form &#nnn(nn); n={0..9} and can be displayed by utf-8 supporting
  7. * browsers. Ascii will not be modified.
  8. *
  9. * code is taken from www.php.net manual comments
  10. * Author: ronen at greyzone dot com
  11. *
  12. * @version $Id$
  13. * @package squirrelmail
  14. * @subpackage encode
  15. * @param $source string of unicode entities [STRING]
  16. * @return a utf-8 encoded string [STRING]
  17. * @access public
  18. */
  19. function charset_encode_utf_8 ($source) {
  20. $utf8Str = '';
  21. $entityArray = explode ("&#", $source);
  22. $size = count ($entityArray);
  23. for ($i = 0; $i < $size; $i++) {
  24. $subStr = $entityArray[$i];
  25. $nonEntity = strstr ($subStr, ';');
  26. if ($nonEntity !== false) {
  27. $unicode = intval (substr ($subStr, 0, (strpos ($subStr, ';') + 1)));
  28. // determine how many chars are needed to reprsent this unicode char
  29. if ($unicode < 128) {
  30. $utf8Substring = chr ($unicode);
  31. }
  32. else if ($unicode >= 128 && $unicode < 2048) {
  33. $binVal = str_pad (decbin ($unicode), 11, "0", STR_PAD_LEFT);
  34. $binPart1 = substr ($binVal, 0, 5);
  35. $binPart2 = substr ($binVal, 5);
  36. $char1 = chr (192 + bindec ($binPart1));
  37. $char2 = chr (128 + bindec ($binPart2));
  38. $utf8Substring = $char1 . $char2;
  39. }
  40. else if ($unicode >= 2048 && $unicode < 65536) {
  41. $binVal = str_pad (decbin ($unicode), 16, "0", STR_PAD_LEFT);
  42. $binPart1 = substr ($binVal, 0, 4);
  43. $binPart2 = substr ($binVal, 4, 6);
  44. $binPart3 = substr ($binVal, 10);
  45. $char1 = chr (224 + bindec ($binPart1));
  46. $char2 = chr (128 + bindec ($binPart2));
  47. $char3 = chr (128 + bindec ($binPart3));
  48. $utf8Substring = $char1 . $char2 . $char3;
  49. }
  50. else {
  51. $binVal = str_pad (decbin ($unicode), 21, "0", STR_PAD_LEFT);
  52. $binPart1 = substr ($binVal, 0, 3);
  53. $binPart2 = substr ($binVal, 3, 6);
  54. $binPart3 = substr ($binVal, 9, 6);
  55. $binPart4 = substr ($binVal, 15);
  56. $char1 = chr (240 + bindec ($binPart1));
  57. $char2 = chr (128 + bindec ($binPart2));
  58. $char3 = chr (128 + bindec ($binPart3));
  59. $char4 = chr (128 + bindec ($binPart4));
  60. $utf8Substring = $char1 . $char2 . $char3 . $char4;
  61. }
  62. if (strlen ($nonEntity) > 1)
  63. $nonEntity = substr ($nonEntity, 1); // chop the first char (';')
  64. else
  65. $nonEntity = '';
  66. $utf8Str .= $utf8Substring . $nonEntity;
  67. }
  68. else {
  69. $utf8Str .= $subStr;
  70. }
  71. }
  72. return $utf8Str;
  73. }
  74. ?>