如何生成混合在一起的随机数字和字母。
这是我的PHP代码。
$i=1;
while($i<=10000){
echo $i++;
}
答案 0 :(得分:5)
这是我使用的功能
function rand_str($n = 32, $str = "abcdefghijklmnopqrstuvwxyz0123456789")
{
$len = strlen($str);
$pin = "";
for($i = 0; $i < $n; $i++)
{
$rand = rand(0, $len - 1);
$letter = substr($str, $rand, 1);
$pin .= $letter;
}
return $pin;
}
答案 1 :(得分:2)
PHP提供函数uniqid()。此功能保证唯一的字符串。 因此,uniqid()的值是相当可预测的,不应该用于加密(顺便说一下,PHPs rand()被认为是相当不可预测的。)
运行uniqid(),以mnd5()为前缀的rand()会给出更多不可预测的值:
$quite_random_token = md5(uniqid(rand(1,6)));
这样做的另一个好处是md5()可以确保32个字符/数字长的哈希值(字符串)。
答案 2 :(得分:2)
通常有一些类型的字符串/文本类允许您以可重用的方式执行此操作,而不是仅仅编写一个函数/编写内联代码。
<?php
class Text
{
/**
* Generate a random string
* @param string $type A type of pool, or a string of characters to use as the pool
* @param integer $length Length of string to return
* @return string
*/
public static function random($type = 'alnum', $length = 8)
{
$pools = array(
'alnum' => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'alpha' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'hexdec' => '0123456789abcdef',
'numeric' => '0123456789',
'nozero' => '123456789',
'distinct' => '2345679ACDEFHJKLMNPRSTUVWXYZ'
);
// Use type as a pool if it isn't preconfigured
$pool = isset($pools[$type]) ? $pools[$type] : $type;
$pool = str_split($pool, 1);
$max = count($pool) - 1;
$str = '';
for ($i = 0; $i < $length; $i++)
{
$str .= $pool[mt_rand(0, $max)];
}
return $str;
}
}
这是一个示例用法: http://codepad.org/xiu7rYQe
答案 3 :(得分:0)
你需要这样的东西:
$chars = 'ABCDEFGHIJKLMNOPQRSTOUVWXYZ0123456789';
$i = 0;
do{
$i++;
$ret .= $ret.$chars[mt_rand(0,35)];
}while($i<$length+1);
答案 4 :(得分:0)
你可以打印一个随机字母数字字符,如下所示:
print chr(rand(97, 122));
检查要返回的ascii字符。 97 = a和122 = z。 (我认为这是对的)
编辑:这几乎是正确的。你必须包括0-9,但这足以让你开始。
答案 5 :(得分:0)
这是我的。
<?php
function randomMixed($length) {
$output = '';
$rand = array_merge(range('a','z'), range('A','Z'), range('0','9'));
for($i = 0; $i < $length; $i++) {
$output .= $rand[array_rand($rand)];
}
return $output;
}
?>
答案 6 :(得分:0)
正如greg0ire所说,你可以按照以下方式使用uniqueid()函数来生成字母数字随机数: printf(“uniqid():%s \ r \ n”,uniqid());