php隨機生成數(shù)字字母組合的方法
更新時間:2015年03月18日 09:45:42 作者:Simael
這篇文章主要介紹了php隨機生成數(shù)字字母組合的方法,實例分析了php生成隨機數(shù)及隨機字母的相關(guān)技巧與用法,非常具有實用價值,需要的朋友可以參考下
本文實例講述了php隨機生成數(shù)字字母組合的方法。分享給大家供大家參考。具體如下:
直接上代碼:
復(fù)制代碼 代碼如下:
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;
}
{
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;
}
例如隨機生成 2 位 字母和數(shù)字組合
只需調(diào)用函數(shù) 并傳參2即可。
echo getRandomString(2);
如果僅僅是生成小寫字母你可以使用類似方法
echo chr(mt_rand(65, 90);
大寫字母
echo chr(mt_rand(97, 122));
希望本文所述對大家的php程序設(shè)計有所幫助。
相關(guān)文章
PHP 雜談《重構(gòu)-改善既有代碼的設(shè)計》之三 重新組織數(shù)據(jù)
承接上文的PHP 雜談《重構(gòu)-改善既有代碼的設(shè)計》之 重新組織你的函數(shù)繼續(xù)重構(gòu)方面的內(nèi)容2012-04-04

