Skip to content

Commit 096046b

Browse files
committed
✨ add utf8_encode() and utf8_decode() functions as a polyfill
Signed-off-by: otengkwame <[email protected]>
1 parent 1961da6 commit 096046b

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

Core/helpers/webby_helper.php

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,80 @@ function unique_id(int $length = 13)
5050
}
5151
}
5252

53+
/* ----------------------------- Polyfill Functions ---------------------------------*/
54+
55+
if ( ! function_exists('utf8_encode'))
56+
{
57+
/**
58+
* A function to restore utf8_encode
59+
*
60+
* @param string $string
61+
* @return string
62+
*/
63+
function utf8_encode($string, $as_obsolete = false)
64+
{
65+
if (!$as_obsolete) {
66+
return mb_convert_encoding($string, 'UTF-8');
67+
}
68+
69+
$string .= $string;
70+
$length = \strlen($string);
71+
72+
for ($i = $length >> 1, $j = 0; $i < $length; ++$i, ++$j) {
73+
switch (true) {
74+
case $string[$i] < "\x80": $string[$j] = $string[$i]; break;
75+
case $string[$i] < "\xC0": $string[$j] = "\xC2"; $string[++$j] = $string[$i]; break;
76+
default: $string[$j] = "\xC3"; $string[++$j] = \chr(\ord($string[$i]) - 64); break;
77+
}
78+
}
79+
80+
return substr($string, 0, $j);
81+
}
82+
}
83+
84+
if ( ! function_exists('utf8_decode'))
85+
{
86+
/**
87+
* A function to restore utf8_decode
88+
*
89+
* @param string $string
90+
* @return string
91+
*/
92+
function utf8_decode($string, $as_obsolete = false)
93+
{
94+
if (!$as_obsolete) {
95+
return mb_convert_encoding($string, 'ISO-8859-1', 'UTF-8');
96+
}
97+
98+
$string = (string) $string;
99+
$length = \strlen($string);
100+
101+
for ($i = 0, $j = 0; $i < $length; ++$i, ++$j) {
102+
switch ($string[$i] & "\xF0") {
103+
case "\xC0":
104+
case "\xD0":
105+
$c = (\ord($string[$i] & "\x1F") << 6) | \ord($string[++$i] & "\x3F");
106+
$string[$j] = $c < 256 ? \chr($c) : '?';
107+
break;
108+
109+
case "\xF0":
110+
++$i;
111+
// no break
112+
113+
case "\xE0":
114+
$string[$j] = '?';
115+
$i += 2;
116+
break;
117+
118+
default:
119+
$string[$j] = $string[$i];
120+
}
121+
}
122+
123+
return substr($string, 0, $j);
124+
}
125+
}
126+
53127
/* ------------------------------- Config Functions ---------------------------------*/
54128

55129
if ( ! function_exists('config'))

0 commit comments

Comments
 (0)