/**
* 測試 shuffleString 函式
*/
function testShuffleString() {
$shuffled = shuffleString("ĄęźćÓ");
if (\mb_strlen($shuffled) != 5) {
throw new \UnexpectedValueException("字元數量不正確");
}
if ($shuffled == "ĄęźćÓ") {
throw new \UnexpectedValueException("字串相同");
}
foreach (["Ą", "ę", "ź", "ć", "Ó"] as $char) {
if (\mb_strpos($shuffled, $char) === false) {
throw new \UnexpectedValueException("找不到字元");
}
}
}
/**
* 隨機排列字串
*
* @param $stringValue 要排列的字串
* @param string $startWith 將 $stringValue 排列後附加到 $startWith
* @return string 排列後的字串
* @author Krzysztof Piasecki<krzysiekpiasecki@gmail.com>
*/
function shuffleString($stringValue, $startWith = "") {
$range = \range(0, \mb_strlen($stringValue));
shuffle($range);
foreach($range as $index) {
$startWith .= \mb_substr($stringValue, $index, 1);
}
return $startWith;
};
testShuffleString();
echo shuffleString("Hello"); // > 'elHol' (類似這樣)
echo shuffleString("World!", "Hello "); // > 'Hello do!lrW' (類似這樣)