php true multi-byte string shuffle function?

Solution:1

Try splitting the string using mb_strlen and mb_substr to create an array, then using shuffle before joining it back together again. (Edit: As also demonstrated in @Frosty Z’s answer.)

An example from the PHP interactive prompt:

php > $string = "Pretend I'm multibyte!";
php > $len = mb_strlen($string);
php > $sploded = array(); 
php > while($len-- > 0) { $sploded[] = mb_substr($string, $len, 1); }
php > shuffle($sploded);
php > echo join('', $sploded);
rmedt tmu nIb'lyi!eteP

You’ll want to be sure to specify the encoding, where appropriate.

Solution:2

This should do the trick, too. I hope.

class String
{

    public function mbStrShuffle($string)
    {
        $chars = $this->mbGetChars($string);
        shuffle($chars);
        return implode('', $chars);
    }

    public function mbGetChars($string)
    {
        $chars = [];

        for($i = 0, $length = mb_strlen($string); $i < $length; ++$i)
        {
            $chars[] = mb_substr($string, $i, 1, 'UTF-8');
        }

        return $chars;
    }

}