Home > Article > Backend Development > A simple implementation method to generate a specified random string in PHP_PHP Tutorial
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.
4 11 12 |
/** * @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); |