Home  >  Article  >  php教程  >  php 随机生成数字字母组合的方法

php 随机生成数字字母组合的方法

WBOY
WBOYOriginal
2016-06-06 20:06:292380browse

直接上代码:

function getRandomString($len, $chars=null)  
{  
    if (is_null($chars)) {  
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  
    }  
    mt_srand(10000000*(double)microtime());  
    for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++) {  
        $str .= $chars[mt_rand(0, $lc)];  
    }  
    return $str;  
}

例如随机生成 6 位 字母和数字组合 

只需调用函数 并传参6即可。

echo getRandomString(6);

如果仅仅是生成小写字母你可以使用类似方法

echo chr(mt_rand(65, 90);

大写字母

echo chr(mt_rand(97, 122));
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