Home > Backend Development > PHP Tutorial > PHP生成指定随机字符串的简单实现方法_php技巧

PHP生成指定随机字符串的简单实现方法_php技巧

WBOY
Release: 2016-05-16 20:18:35
Original
1089 people have browsed it

本文实例讲述了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);
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template