Home  >  Article  >  类库下载  >  PHP: universal random string generation function

PHP: universal random string generation function

高洛峰
高洛峰Original
2016-10-10 10:21:041163browse

Used for verification code, and then encapsulate this function. When using it, you need to set 2 parameters:

  The string to be collected in the $str setting, such as:

 $str='efasfgzsrhftjxjxjhsrth';

Then the string generated in the function will be randomly grabbed from efasfgzsrhftjxjxjhsrth;

 $codeLen sets the random string to be generated, and if it is set to 5, 5 random strings will be generated.

Principle: Randomly grab strings and splice the strings

Effect:

PHP: universal random string generation function

Code:

<span style="font-size: 18px;"><?php
 
//mt_rand  获取随机数 mt_rand(min, max);
$str="abcdefghijkmnpqrstuvwxyz0123456789ABCDEFGHIGKLMNPQRSTUVWXYZ";//设置被随机采集的字符串
$codeLen=&#39;5&#39;;//设置生成的随机数个数
 
function  str_rand($str,$codeLen){
    $rand="";
    for($i=0; $i<$codeLen-1; $i++){
        $rand .= $str[mt_rand(0, strlen($str)-1)];  //如:随机数为30  则:$str[30]
    }
   return $rand;
}
$code=str_rand($str,$codeLen);
echo $code;</span><br><span style="font-size: 18px;">?></span>


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

Related articles

See more