Home >Backend Development >PHP Tutorial >How to combine letters and numbers in PHP random numbers? The first two are letters followed by numbers?
How to combine letters and numbers in PHP random numbers? The first two are letters followed by numbers?
How to combine letters and numbers in PHP random numbers? The first two are letters followed by numbers?
The idea mentioned above is correct. It is normal for repetition to occur if the random number is too large. I wrote a method according to your needs. If you are interested, you can run it a million times to see what the probability of repetition is.
<code>function getRandomString($prefixLength = 2, $suffixLength = 6) { $t = ''; for ($i=0; $i<$prefixLength; $i++) { $salt = mt_rand(1000, 9999); if ($salt % 2) { $t .= chr(mt_rand(97,122)); } else { $t .= chr(mt_rand(65,90)); } } $min = intval(str_pad('1', $suffixLength, '0', STR_PAD_RIGHT)); $max = intval(str_repeat('9', $suffixLength)); return $t . mt_rand($min, $max); } </code>
First generate random letters and then generate random numbers, but this may cause duplication. If you want to avoid duplication as much as possible, you can only start with the following numbers. Please try the following example
<code>function randomKey(){ $re = ''; $letter = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; while(strlen($re)<2) { $re .= $letter[rand(0, strlen($letter)-1)]; /** 从$letter中随机产生一个字符 */ } $_rand = mt_rand(10000000, 99999999); /** 生成8位随机数 */ list($usec, $sec) = explode(" ", microtime()); /** 获取微秒时间戳 */ $microtime = str_replace(".", "", ((float)$usec + (float)$sec)); /** 处理字符串 */ $result = $re.$_rand.$microtime; }</code>
The random number generated in this way may be a bit long. You can remove the random number or directly use letters and subtle timestamps. For reference only
Can’t you just put two random letters in some random arrays and then splice them together? Or have special needs?