本文介紹了生成隨機 5 個字符的字符串的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我想創建精確的 5 個隨機字符串,并且復制的可能性最小.最好的方法是什么?謝謝.
I want to create exact 5 random characters string with least possibility of getting duplicated. What would be the best way to do it? Thanks.
推薦答案
$rand = substr(md5(microtime()),rand(0,26),5);
這可能是我最好的猜測——除非您也在尋找特殊字符:
Would be my best guess--Unless you're looking for special characters, too:
$seed = str_split('abcdefghijklmnopqrstuvwxyz'
.'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
.'0123456789!@#$%^&*()'); // and any other characters
shuffle($seed); // probably optional since array_is randomized; this may be redundant
$rand = '';
foreach (array_rand($seed, 5) as $k) $rand .= $seed[$k];
示例
而且,對于基于時鐘的一個(因為它是增量的,所以沖突更少):
And, for one based on the clock (fewer collisions since it's incremental):
function incrementalHash($len = 5){
$charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
$base = strlen($charset);
$result = '';
$now = explode(' ', microtime())[1];
while ($now >= $base){
$i = $now % $base;
$result = $charset[$i] . $result;
$now /= $base;
}
return substr($result, -5);
}
注意:增量意味著更容易猜測;如果您將其用作鹽或驗證令牌,請不要使用.WCWyb"的鹽(現在)意味著 5 秒后它是WCWyg")
這篇關于生成隨機 5 個字符的字符串的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!