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

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

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

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

 具体分析如下:

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

/**

* @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

$str_list .= $$case[$i];

}

return substr(str_shuffle($str_list),0,$length);

}

echo randomString("number,upper,lower",12);

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