ae73daec0bbb655474694f140d307ba5d1a47d32
[squirrelmail.git] / functions / encode / utf_8.php
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 * @package squirrelmail
13 * @subpackage encode
14 * @param $source string of unicode entities [STRING]
15 * @return a utf-8 encoded string [STRING]
16 * @access public
17 */
18 function charset_encode_utf_8 ($source) {
19 $utf8Str = '';
20 $entityArray = explode ("&#", $source);
21 $size = count ($entityArray);
22 for ($i = 0; $i < $size; $i++) {
23 $subStr = $entityArray[$i];
24 $nonEntity = strstr ($subStr, ';');
25 if ($nonEntity !== false) {
26 $unicode = intval (substr ($subStr, 0, (strpos ($subStr, ';') + 1)));
27 // determine how many chars are needed to reprsent this unicode char
28 if ($unicode < 128) {
29 $utf8Substring = chr ($unicode);
30 }
31 else if ($unicode >= 128 && $unicode < 2048) {
32 $binVal = str_pad (decbin ($unicode), 11, "0", STR_PAD_LEFT);
33 $binPart1 = substr ($binVal, 0, 5);
34 $binPart2 = substr ($binVal, 5);
35
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
46 $char1 = chr (224 + bindec ($binPart1));
47 $char2 = chr (128 + bindec ($binPart2));
48 $char3 = chr (128 + bindec ($binPart3));
49 $utf8Substring = $char1 . $char2 . $char3;
50 }
51 else {
52 $binVal = str_pad (decbin ($unicode), 21, "0", STR_PAD_LEFT);
53 $binPart1 = substr ($binVal, 0, 3);
54 $binPart2 = substr ($binVal, 3, 6);
55 $binPart3 = substr ($binVal, 9, 6);
56 $binPart4 = substr ($binVal, 15);
57
58 $char1 = chr (240 + bindec ($binPart1));
59 $char2 = chr (128 + bindec ($binPart2));
60 $char3 = chr (128 + bindec ($binPart3));
61 $char4 = chr (128 + bindec ($binPart4));
62 $utf8Substring = $char1 . $char2 . $char3 . $char4;
63 }
64
65 if (strlen ($nonEntity) > 1)
66 $nonEntity = substr ($nonEntity, 1); // chop the first char (';')
67 else
68 $nonEntity = '';
69
70 $utf8Str .= $utf8Substring . $nonEntity;
71 }
72 else {
73 $utf8Str .= $subStr;
74 }
75 }
76
77 return $utf8Str;
78 }
79 ?>