For a unicode-safe shuffling;
<?php
$r = new \Random\Randomizer();
$s = join($r->shuffleArray(mb_str_split($string)));
(PHP 8 >= 8.2.0)
Random\Randomizer::shuffleBytes β Get a byte-wise permutation of a string
Returns a uniformly selected permutation of the input bytes
.
Each possible permutation of the input bytes
is equally likely to be returned.
A permutation of the bytes of bytes
.
Random\Randomizer::$engine
.
Example #1 Random\Randomizer::shuffleBytes() example
<?php
$r = new \Random\Randomizer();
// Shuffle bytes in a string:
echo "Β«", $r->shuffleBytes("PHP is great!"), "Β»\n";
?>
The above example will output something similar to:
Β« ga rHs!PPietΒ»
Example #2 Byte-wise shuffling breaks Unicode characters
<?php
$r = new \Random\Randomizer();
$unicode = "π, π₯, π, π, π";
$shuffled = $r->shuffleBytes( $unicode );
// Byte-wise shuffling of non-ASCII characters destroys them,
// resulting in invalid sequences (indicated by the Unicode
// replacement character) or even entirely different characters
// appearing in the output.
echo "Original: ", $unicode, "\n";
echo "Shuffled: Β«", $shuffled, "Β»\n";
echo "Shuffled Bytes: ", bin2hex($shuffled), "\n";
?>
The above example will output something similar to:
Original: π, π₯, π, π, π Shuffled: Β«οΏ½ οΏ½οΏ½,οΏ½οΏ½οΏ½οΏ½οΏ½π,οΏ½ οΏ½οΏ½ οΏ½, οΏ½,οΏ½οΏ½Β» Shuffled Bytes: 87208e912c8d9fa5f0f0f09f8d9f2cf09f208c9d20f02c209f2c8d8d
For a unicode-safe shuffling;
<?php
$r = new \Random\Randomizer();
$s = join($r->shuffleArray(mb_str_split($string)));