我试图在PHP中创建一个随机字符串,我得到绝对没有输出:
<?php
function RandomString()
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randstring = '';
for ($i = 0; $i < 10; $i++) {
$randstring = $characters[rand(0, strlen($characters))];
}
return $randstring;
}
RandomString();
echo $randstring;
我做错了什么?
$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)));
递归解决方案:
public static function _random(string $set , int $length): string
{
$setLength = strlen($set);
$randomKey = random_int(0, $setLength - 1);
$firstPiece = substr($set, 0, $randomKey);
$secondPiece = substr($set, $randomKey, $setLength - $randomKey);
$removedCharacter = $firstPiece[strlen($firstPiece) - 1] ?? null;
if(null === $removedCharacter || $length === 0) {
return '';
}
$firstPieceWithoutTheLastChar = substr($firstPiece, 0, -1);
return $removedCharacter . self::_random($firstPieceWithoutTheLastChar . $secondPiece, $length - 1);
}
不错的表现,https://3v4l.org/aXaJ6/perf
只使用PHP本地函数的参数化一行程序,从PHP 5.1.0开始工作
str_shuffle(implode('', (array_intersect_key(($map = array_map('chr', array_merge(array_map('mt_rand', array_fill(0, $length = 25, 48), array_fill(0,$length,57)),array_map('mt_rand', array_fill(0, $length, 65), array_fill(0,$length,90)),array_map('mt_rand', array_fill(0, $length, 97), array_fill(0,$length,122))))), array_flip($keys = array_rand($map, $length))))))