5

I am trying out the following

$x = "126·10⁴";
$array = str_split($x);
echo "x = " . $x . "<br>";
echo "Array length: " . count($array) . "<br>";

 echo "Charset: " .mb_detect_encoding($x)."<br>";

foreach($array as $i)
    echo $i .  " ";

which gives as output:

x = 126·10⁴
Array length: 10
Charset: UTF-8
1 2 6 � � 1 0 � � �

I want the · and to be 1 character in the array, how can this be done? What I am trying to reach is to iterate over all characters of a string, so any other solution is also welcome.

2

1 Answer 1

2

According to a comment in the PHP Manual (Thanks to @Rizier123), the proper way to do this is as following:

function str_split_unicode($str, $l = 0) {
    if ($l > 0) {
        $ret = array();
        $len = mb_strlen($str, "UTF-8");
        for ($i = 0; $i < $len; $i += $l) {
            $ret[] = mb_substr($str, $i, $l, "UTF-8");
        }
        return $ret;
    }
    return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
}
Sign up to request clarification or add additional context in comments.

1 Comment

This function helps me in my base64_decode string. Thanks for this answer!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.