Home >php教程 >php手册 >PHP study notes: Universal random string generation function (already encapsulated)

PHP study notes: Universal random string generation function (already encapsulated)

WBOY
WBOYOriginal
2016-09-14 09:24:001129browse

Used to make verification codes, 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. If set to 5, 5 random strings will be generated.

Principle: randomly grab strings and splice the strings

Effect:

Code:

<span style="font-size: 18px;"><?php

//mt_rand  获取随机数 mt_rand(min, max);
$str="abcdefghijkmnpqrstuvwxyz0123456789ABCDEFGHIGKLMNPQRSTUVWXYZ";//设置被随机采集的字符串
$codeLen='5';//设置生成的随机数个数

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