首页 > 开发 > PHP > 正文

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

2024-05-04 23:35:49
字体:大 中 小
来源:转载
供稿:网友

本文实例讲述了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. */ 

希望本文所述对大家的php程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表