Home >php教程 >php手册 >PHP生成指定随机字符串的简单实现方法,php生成字符串

PHP生成指定随机字符串的简单实现方法,php生成字符串

WBOY
WBOYOriginal
2016-06-13 09:08:02895browse

PHP生成指定随机字符串的简单实现方法,php生成字符串

本文实例讲述了PHP生成指定随机字符串的简单实现方法。分享给大家供大家参考。具体分析如下:

这是一个简单的函数,没有对生成的内容作强制设定。所以在生成的字符串长度较少的时候,会出现没有指定类型字符的情况。当然,修改起来也很简单,这里就不做添加了。

/**
 * @param string $type
 * @param $length
 * @return string
 */
function randomString($type="number,upper,lower",$length){
  $valid_type = array('number','upper','lower');
  $case = explode(",",$type);
  $count = count($case);
  //根据交集判断参数是否合法
  if($count !== count(array_intersect($case,$valid_type))){
    return false;
  }
  $lower = "abcdefghijklmnopqrstuvwxyz";
  $upper = strtoupper($lower);
  $number = "0123456789";
  $str_list = "";
  for($i=0;$i<$count;++$i){
    $str_list .= $$case[$i];
  }
  return substr(str_shuffle($str_list),0,$length);
}
echo randomString("number,upper,lower",12);

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn