在 PHP 中生成特定长度和限制的唯一随机字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5444877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generating a unique random string of a certain length and restrictions in PHP?
提问by AKor
I have the need to generate a random alphanumeric string of 8 characters. So it should look sort of like b53m1isM
for example. Both upper and lower case, letters and numbers.
我需要生成一个随机的 8 个字符的字母数字字符串。所以它应该看起来有点像b53m1isM
。大写和小写,字母和数字。
I already have a loop that runs eight times and what I want it to do is to concatenate a string with a new random character every iteration.
我已经有一个运行八次的循环,我希望它做的是在每次迭代时将一个字符串与一个新的随机字符连接起来。
Here's the loop:
这是循环:
$i = 0;
while($i < 8)
{
$randPass = $randPass + //random char
$i = $i + 1;
}
Any help?
有什么帮助吗?
回答by ThiefMaster
function getRandomString($length = 8) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$string = '';
for ($i = 0; $i < $length; $i++) {
$string .= $characters[mt_rand(0, strlen($characters) - 1)];
}
return $string;
}
回答by Dejan Marjanovic
function randr($j = 8){
$string = "";
for($i=0; $i < $j; $i++){
$x = mt_rand(0, 2);
switch($x){
case 0: $string.= chr(mt_rand(97,122));break;
case 1: $string.= chr(mt_rand(65,90));break;
case 2: $string.= chr(mt_rand(48,57));break;
}
}
return $string;
}
echo randr(); // b53m1isM
回答by Vasin Yuriy
$permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Output: m-swm3AP8X50VG4jCi.jpg
echo 'm-'.substr(str_shuffle($permitted_chars), 0, 16).'.jpg';