在 [$min, $max] 范围内随机取长度,截取字符串前段放入数组,循环直到字符串耗尽。
<?php
function RandomSplit($min, $max, $str) {
$result = array();
while ($str !== '') {
$len = mt_rand($min, $max);
$len = min($len, strlen($str)); // 防止越界
$result[] = substr($str, 0, $len);
$str = substr($str, $len);
}
return $result;
}
// 测试
$str = 'This is a example to test the RandomSplit function.';
print_r(RandomSplit(1, 7, $str));
/* 示例输出(每次不同):
Array
(
[0] => This
[1] => is a
[2] => examp
[3] => le to t
[4] => est th
[5] => e Rand
[6] => omSpli
[7] => t funct
[8] => ion.
)
*/
function mbRandomSplit($min, $max, $str, $encoding = 'UTF-8') {
$result = array();
$len = mb_strlen($str, $encoding);
$pos = 0;
while ($pos < $len) {
$step = mt_rand($min, $max);
$step = min($step, $len - $pos);
$result[] = mb_substr($str, $pos, $step, $encoding);
$pos += $step;
}
return $result;
}