Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/240.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP将字符串输出向上随机插入数组_Php - Fatal编程技术网

PHP将字符串输出向上随机插入数组

PHP将字符串输出向上随机插入数组,php,Php,我试图找到最好的方法来随机拆分字符串 例如: $variable1 = "this_is_the_string_contents"; 我试图实现的输出是这样的 "is" "this" "ents" "cont" "_" etc etc 最好的方法是什么。我不知道什么PHP函数最适合我一直在研究的任务,foreach()、rand()等的组合。$str=“this_is_the_string_contents”; $stringPiece=str_split($str,4)//在这里输入块大小

我试图找到最好的方法来随机拆分字符串

例如:

$variable1 = "this_is_the_string_contents";
我试图实现的输出是这样的

"is"
"this"
"ents"
"cont"
"_"
etc
etc
最好的方法是什么。我不知道什么PHP函数最适合我一直在研究的任务,foreach()、rand()等的组合。

$str=“this_is_the_string_contents”;
$stringPiece=str_split($str,4)//在这里输入块大小的任意数字
印刷品($stringPiece);
如果愿意,可以使用rand()为块大小生成一个随机数。根据您试图执行的操作,可能需要考虑删除空格/下划线。

$str=“这是字符串内容”;
$stringPiece=str_split($str,4)//在这里输入块大小的任意数字
印刷品($stringPiece);

如果愿意,可以使用rand()为块大小生成一个随机数。根据您试图执行的操作,可能需要考虑删除空格/下划线。

这将把字符串分解为随机长度的子字符串数组

$l = strlen($variable1);
$i = 0;                                       // holds the current string position

while ($i < $l) {
    $r = rand(1, $l - $i);                    // get a random length for the next substring
    $chunks[] = substr($variable1, $i, $r);   // add the substring to the array
    $i += $r;                                 // increment $i by the substring length
}
而不是您展示的更均匀分布的示例。如果您想避免这种情况,您可以稍微“去随机化”随机长度部分

if ($l - $i > $i) {
    $r = rand(1, ($l - $i) / 2);
} else {
    $r = rand(1, $l - $i);        
}
这将防止子字符串占用字符串的一半以上,直到字符串的一半消失


拥有子字符串数组后,还可以使用

shuffle($chunks); 

这将把一个字符串分解成一个随机长度的子字符串数组

$l = strlen($variable1);
$i = 0;                                       // holds the current string position

while ($i < $l) {
    $r = rand(1, $l - $i);                    // get a random length for the next substring
    $chunks[] = substr($variable1, $i, $r);   // add the substring to the array
    $i += $r;                                 // increment $i by the substring length
}
而不是您展示的更均匀分布的示例。如果您想避免这种情况,您可以稍微“去随机化”随机长度部分

if ($l - $i > $i) {
    $r = rand(1, ($l - $i) / 2);
} else {
    $r = rand(1, $l - $i);        
}
这将防止子字符串占用字符串的一半以上,直到字符串的一半消失


拥有子字符串数组后,还可以使用

shuffle($chunks); 

可能尝试使用and
rand
strlen
和朋友。可能尝试使用and
rand
strlen
和朋友们。感谢你们的帮助,我将你们的答案标记为解决方案:)另外@EdCottrell你们的答案在被删除之前这个网站非常有用,所以也感谢你们分享一个演示链接。感谢你们的帮助,我将你们的答案标记为解决方案:)另外@EdCottrell你们的答案在被删除之前这个网站非常有用非常有用,谢谢分享演示链接。