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

yipeiwu_com6年前PHP代码库

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

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

function RandomSplit($min, $max, $str){
  $a = array();
  while ($str != ''){
    $p = rand($min, $max);
    $p = ($p > strlen($str)) ? strlen($str) : $p;
    $buffer = substr($str, 0, $p);
    $str = substr($str, $p, strlen($str)-$p);
    $a[] = $buffer;
  }
  return $a;
}
//范例:
/*
** Example:
*/
$test_string = 'This is a example to test the RandomSplit function.';
print_r(RandomSplit(1, 7, $test_string));
/*
Outputs something like this
(Array items are 1 to 7 characters long): 
Array
(
  [0] => This
  [1] => is
  [2] => a exam
  [3] => ple to
  [4] => test t
  [5] => he
  [6] => 
  [7] => ran
  [8] => d_spl
  [9] => it f
  [10] => un
  [11] => ction.
)
*/

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

相关文章

PHP7安装Redis扩展教程【Linux与Windows平台】

本文实例讲述了PHP7安装Redis扩展的方法。分享给大家供大家参考,具体如下: linux中PHP7安装Redis扩展 1.依次执行 wget -c https://github....

同一空间绑定多个域名而实现访问不同页面的PHP代码

<?php  switch ($_SERVER["HTTP_HOST"]) {      case&...

PHP SPL使用方法和他的威力

SPL,PHP 标准库(Standard PHP Library) ,此从 PHP 5.0 起内置的组件和接口,并且从 PHP5.3 已逐渐的成熟。SPL 其实在所有的 PHP5 开发环...

php常用正则函数实例小结

本文实例总结了php常用正则函数。分享给大家供大家参考,具体如下: 1. mixed preg_replace(mixed pattern, mixed  replacemen...

php删除文本文件中重复行的方法

本文实例讲述了php删除文本文件中重复行的方法。分享给大家供大家参考。具体分析如下: 这个php函数用来删除文件中的重复行,还可以指定是否忽略大小写,和指定换行符 /** * Re...