我试图在PHP中创建一个随机字符串,我得到绝对没有输出:
<?php
function RandomString()
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randstring = '';
for ($i = 0; $i < 10; $i++) {
$randstring = $characters[rand(0, strlen($characters))];
}
return $randstring;
}
RandomString();
echo $randstring;
我做错了什么?
我已经测试了那里最流行的函数的性能,在我的盒子上生成1 000 000个32个符号的字符串所需的时间是:
2.5 $s = substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,32);
1.9 $s = base64_encode(openssl_random_pseudo_bytes(24));
1.68 $s = bin2hex(openssl_random_pseudo_bytes(16));
0.63 $s = base64_encode(random_bytes(24));
0.62 $s = bin2hex(random_bytes(16));
0.37 $s = substr(md5(rand()), 0, 32);
0.37 $s = substr(md5(mt_rand()), 0, 32);
请注意,它到底有多长并不重要,重要的是哪个更慢,哪个更快,因此您可以根据您的要求进行选择,包括密码准备等。
如果需要小于32个字符的字符串,则在MD5周围添加substr()以保证准确性。
为了回答:字符串没有被连接,而是被覆盖,函数的结果没有被存储。
function randomName($length = 8) {
$values = array_merge(range(65, 90), range(97, 122), range(48, 57));
$max = count($values) - 1;
$str = chr(mt_rand(97, 122));
for ($i = 1; $i < $length; $i++) {
$str .= chr($values[mt_rand(0, $max)]);
}
return $str;
}
$t = array_merge(range('0', '9'), range('a', 'z'), range('A', 'Z'));
echo join('', array_map(function() use($t) { return $t[array_rand($t)]; }, range(1, 15)));
或一行程序
echo join('', array_map(function() { return substr('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', rand(0, 61), 1); }, range(1, 15)));
<?php
/**
* Creates a random string
*
* @param (int) $length
* Length in characters
* @param (array) $ranges
* (optional) Array of ranges to be used
*
* @return
* Random string
*/
function random_string($length, $ranges = array('0-9', 'a-z', 'A-Z')) {
foreach ($ranges as $r) $s .= implode(range(array_shift($r = explode('-', $r)), $r[1]));
while (strlen($s) < $length) $s .= $s;
return substr(str_shuffle($s), 0, $length);
}
// Examples:
$l = 100;
echo '<b>Default:</b> ' . random_string($l) . '<br />';
echo '<b>Lower Case only:</b> ' . random_string($l, array('a-z')) . '<br />';
echo '<b>HEX only:</b> ' . random_string($l, array('0-9', 'A-F')) . '<br />';
echo '<b>BIN only:</b> ' . random_string($l, array('0-1')) . '<br />';
/* End of file */