PHP簡單生成隨機字串

來源:文萃谷 1.84W

此函式建立一個隨機字串,可以作為使用者的隨機密碼等,有需要的朋友可以參考下。

PHP簡單生成隨機字串

/**

* 生成隨機字串

* @param string $lenth 長度

* @return string 字串

*/

function get_randomstr($lenth = 6) {

return get_random($lenth, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');

}

/**

* 產生隨機字串

*

* @param int $length 輸出長度

* @param string $chars 可選的 ,預設為 0123456789

* @return string 字串

*/

function get_random($length, $chars = '0123456789') {

$hash = '';

$max = strlen($chars) - 1;

for($i = 0; $i < $length; $i++) {

$hash .= $chars[mt_rand(0, $max)];

}

return $hash;

}

使用方法:

1

2

echo get_randomstr(6);

echo get_randomstr(7);

輸出:

1

2

vS8wZK

hQ17fEI

以上的這兩個結果都會隨機生成,每次執行的.結構都會不一樣。

解析:

通過引數傳入生成字串的個數給方法get_randomstr();get_randomstr()方法再通過get_random方法生成隨機數返回給get_randomstr(),其實這一過程是通過兩個自定義方法來完成的,我個人也覺得比較繁瑣,雖然思路是清晰的。其實這種方法的好處就是當我們在公共方法把get_random方法寫死的時候,如果後面發現有些功能是get_random不能滿足的事情下,我們可以通過get_randomstr方法來擴充套件

熱門標籤