Home  >  Article  >  Backend Development  >  A simple implementation method to generate a specified random string in PHP_PHP Tutorial

A simple implementation method to generate a specified random string in PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 09:58:35818browse

A simple implementation method for PHP to generate a specified random string

The specific analysis is as follows:

This is a simple function with no mandatory settings for the generated content. Therefore, when the length of the generated string is small, there will be situations where there are no specified type characters. Of course, it is very simple to modify, so I won’t add it here.

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<$count; $i){

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

}

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

}

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

1 2 3

4

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); //Determine whether the parameters are legal based on the intersection 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);
http://www.bkjia.com/PHPjc/977615.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/977615.htmlTechArticleThe simple implementation method of PHP generating a specified random string is analyzed as follows: This is a simple function, there is no need to generate The content is forced to be set. Therefore, the length of the generated string is longer...
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