Home >Backend Development >PHP Tutorial >A simple implementation method for PHP to generate a specified random string, PHP generates a string_PHP tutorial
The example in this article describes a simple implementation method for PHP to generate a specified random string. Share it with everyone for your reference. 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.
/** * @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);
I hope this article will be helpful to everyone’s PHP programming design.