Generating Random 5-Character Strings with Minimal Duplication
Question: How can I efficiently generate a string with exactly 5 random characters with the lowest probability of duplication?
Answer:
Method 1:
<code class="php">$rand = substr(md5(microtime()), rand(0, 26), 5);</code>
Method 2:
<code class="php">$seed = str_split('abcdefghijklmnopqrstuvwxyz' . 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . '0123456789!@#$%^&*()'); shuffle($seed); $rand = ''; foreach (array_rand($seed, 5) as $k) $rand .= $seed[$k];</code>
Method 3:
<code class="php">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); }</code>
Note: For high-security applications, it's recommended to use a more robust random number generator.
The above is the detailed content of How to Generate Random 5-Character Strings with Minimal Duplication?. For more information, please follow other related articles on the PHP Chinese website!