Preface
Generally speaking, when we are making programs, we will definitely use random strings in many places, such as for verification codes. Then we encapsulate this function and set it when using it. 2 parameters, the principle is to randomly grab strings and splice the strings
$str settings to be collected strings, such as
$str=´jfowef34098094j3204efa234sfg2z23srhftj345xjxjhsrth´;
The string generated in the function will be randomly grabbed from $str
$codeLen sets the random string to be generated, set it to 5, and then generate 5 random strings, such as
$codeLen=´5´;//设置生成的随机数个数
The code is as follows
<?php //mt_rand 获取随机数 mt_rand(min, max); //设置被随机采集的字符串 $str="abcdefghijkmnpqrstuvwxyz0123456789ABCDEFGHIGKLMNPQRSTUVWXYZ"; //设置生成的随机数个数 $codeLen=´5´; function str_rand($str,$codeLen){ $rand=""; for($i=0; $i<$codeLen-1; $i ){ //如:随机数为30 则:$str[30] $rand .= $str[mt_rand(0, strlen($str)-1)]; } return $rand; } $code=str_rand($str,$codeLen); echo $code; ?>
Summary
The above is the complete method of generating random strings, except where the verification code can be used It can also be used in other places. I hope the content of this article can bring some help to everyone's study or work. If you have any questions, you can leave a message to communicate.
For more articles related to the PHP encapsulation function to generate random string verification codes, please pay attention to the PHP Chinese website!