php - 使用 chr + rand 生成随机字符 (A-Z)

标签 php

我正在使用以下代码从 A-Z 生成随机字符,但它偶尔会生成 @ 符号。知道如何防止这种情况吗?也许字符范围不正确?

$letter = chr(64+rand(0,26));

最佳答案

使用它更容易。

大写

$letter = chr(rand(65,90));

小写

$letter = chr(rand(97,122));

ascii chart

下面的代码生成 $length 的随机字母数字字符串。你可以在那里看到你需要的数字。

function izrand($length = 32) {

                $random_string="";
                while(strlen($random_string)<$length && $length > 0) {
                        $randnum = mt_rand(0,61);
                        $random_string .= ($randnum < 10) ?
                                chr($randnum+48) : ($randnum < 36 ? 
                                        chr($randnum+55) : $randnum+61);
                 }
                return $random_string;
}

update: 12/19/2015

这是上述函数的更新版本,它增加了生成随机数字键或字母数字键的能力。要生成数字,只需添加 第二个参数为 true

Example Usage

$randomNumber = izrand(32, true);//生成 32 位数字作为字符串 $randomAlphaNumeric = izrand();//生成 32 位字母数字字符串

Typecast to Integer

如果你想将数字类型转换为整数,只需在你之后执行此操作 生成数。注意:这将删除任何前导零(如果存在)。

$randomNumber = (int) $randomNumber;

izrand() v2

function izrand($length = 32, $numeric = false) {

    $random_string = "";
    while(strlen($random_string)<$length && $length > 0) {
        if($numeric === false) {
            $randnum = mt_rand(0,61);
            $random_string .= ($randnum < 10) ?
                chr($randnum+48) : ($randnum < 36 ? 
                    chr($randnum+55) : chr($randnum+61));
        } else {
            $randnum = mt_rand(0,9);
            $random_string .= chr($randnum+48);
        }
    }
    return $random_string;
}

关于php - 使用 chr + rand 生成随机字符 (A-Z),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31441050/

相关文章:

php - 404 页面中的 Laravel 本地化

php - 在 mysql select foreach 之后更新行

php - PHP Soap Server 缓存响应的问题

php - 如何从不同的表中查找值?

php - 如何统计mysql pdo中句子中的单词数

php fopen 返回 false 但文件可读/可写

php - 我们可以在Codeigniter中定义常量数组吗?

php - 用于 API 和非 API 使用的 Laravel 资源 Controller

PHP 检查列是否已填充

php - 将 mysql 更改为 mysqli 时出现 fatal error : Using $this when not in object context in,