產生固定長度的隨機字串
您尋求開發一種方法,以最少的重複有效地產生5 個字元的隨機字串可能性。考慮以下方法:
$rand = substr(md5(microtime()),rand(0,26),5);
此方法利用MD5 雜湊並從隨機產生的雜湊中傳回5 個字元string.
$seed = str_split('abcdefghijklmnopqrstuvwxyz' .'ABCDEFGHIJKLMNOPQRSTUVWXYZ' .'0123456789!@#$%^&*()'); shuffle($seed); // optional $rand = ''; foreach (array_rand($seed, 5) as $k) $rand .= $seed[$k];
此方法產生一個字元陣列並將其打亂以進行隨機化。它選擇 5 個字元並將它們附加到字串中。
function incrementalHash($len = 5){ $charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; $base = strlen($charset); $result = ''; $now = explode(' ', microtime())[1]; while ($now >= $base){ $i = (int)$now % $base; $result = $charset[$i] . $result; $now /= $base; } return substr(str_repeat($charset[0], $len) . $result, -$len); }
此方法利用微時間產生基於當前時間的偽隨機雜湊字符串。它產生逐漸變化的雜湊值。請注意,此方法對於敏感資料可能不太安全。
以上是如何有效率地產生固定長度的隨機字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!