当前位置:首页 > PHP教程 > php数组 > 列表

php将字符串随机分割成不同长度数组的方法

发布:smiling 来源: PHP粉丝网  添加日期:2021-05-27 14:23:40 浏览: 评论:0 

这篇文章主要介绍了php将字符串随机分割成不同长度数组的方法,涉及随机数及字符串操作的相关技巧,需要的朋友可以参考下。

本文实例讲述了php将字符串随机分割成不同长度数组的方法,分享给大家供大家参考,具体分析如下:

这里使用php对字符串在指定的长度范围内进行随机分割,把分割后的结果存在数组里面:

  1. function RandomSplit($min, $max, $str){ 
  2.   $a = array(); 
  3.   while ($str != ''){ 
  4.     $p = rand($min, $max); 
  5.     $p = ($p > strlen($str)) ? strlen($str) : $p; 
  6.     $buffer = substr($str, 0, $p); 
  7.     $str = substr($str, $p, strlen($str)-$p); 
  8.     $a[] = $buffer; 
  9.   } 
  10.   return $a; 
  11. } 
  12. //范例: 
  13. /* 
  14. ** Example: 
  15. */ 
  16. $test_string = 'This is a example to test the RandomSplit function.'; 
  17. print_r(RandomSplit(1, 7, $test_string)); 
  18. /* 
  19. Outputs something like this 
  20. (Array items are 1 to 7 characters long):  
  21. Array 
  22. ( 
  23.   [0] => This 
  24.   [1] => is 
  25.   [2] => a exam 
  26.   [3] => ple to 
  27.   [4] => test t 
  28.   [5] => he 
  29.   [6] =>  
  30.   [7] => ran 
  31.   [8] => d_spl 
  32.   [9] => it f 
  33.   [10] => un 
  34.   [11] => ction. 
  35. ) 
  36. */

Tags: php字符串随机 php数组

分享到: