gpt4 book ai didi

PHP 随机字符串生成器

转载 作者:IT老高 更新时间:2023-10-28 11:35:49 25 4
gpt4 key购买 nike

我正在尝试在 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. $randstring 回显时不在作用域内。
  2. 字符没有在循环中连接在一起。

这是一个包含更正的代码片段:

function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}

通过下面的调用输出随机字符串:

// Echo the random string.
// Optionally, you can give it a desired string length.
echo generateRandomString();

Please note that this generates predictable random strings. If you want to create secure tokens, see this answer.

关于PHP 随机字符串生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4356289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com