请尝试这个函数来生成一个自定义的随机字母数字字符串:
<?php
function random_alphanumeric($length) {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12345689';
$my_string = '';
for ($i = 0; $i < $length; $i++) {
$pos = random_int(0, strlen($chars) -1);
$my_string .= substr($chars, $pos, 1);
}
return $my_string;
}
?>
你可以通过将字符串的长度传递给函数来调整结果,如下所示:
$test_with_50_items = random_alphanumeric(50); // 50 characters
echo $test_with_50_items;
示例(test_with_50_items): Y1FypdjVbFCFK6Gh9FDJpe6dciwJEfV6MQGpJqAfuijaYSZ86
如果你需要超过50个字符或更少,只需按你喜欢的方式调用函数:
$test_with_27_items = random_alphanumeric(27); // 27 characters
echo $test_with_27_items;
如果你需要两个或更多唯一的字符串,你可以使用while循环,这样你肯定会得到两个唯一的字符串…你可以用更多的弦做同样的事情,唯一的限制是你的幻想……
$string_1 = random_alphanumeric(50);
$string_2 = random_alphanumeric(50);
while ($string_1 == $string_2) {
$string_1 = random_alphanumeric(50);
$string_2 = random_alphanumeric(50);
if ($string_1 != $string_2) {
break;
}
}
echo $string_1;
echo "<br>\n";
echo $string_2;
$string_1: KkvUwia8rbDEV2aChWqm3AgeUZqyrRbUx2AxVhx5s4TSJ2VwA4
$string_2: XraO85YfxBBCInafvwipSOJwLmk6JMWiuWOxYQDnXohcn2D8K6
根据PHP 8.3, random_int()是“默认安全的”