doushu5805 2015-07-15 21:03
浏览 225
已采纳

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

I'm using the following to generate a random character from A-Z, but it's occasionally generating the @ symbol. Any idea how to prevent this? Maybe the character range is incorrect?

$letter = chr(64+rand(0,26));
  • 写回答

5条回答 默认 最新

  • doutiao2540 2015-07-15 21:32
    关注

    Use this it's easier.

    Upper Case

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

    Lowercase

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

    ascii chart

    The code below generates a random alpha-numeric string of $length. You can see the numbers there for what you need.

    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

    Here is an updated version of the function above, it adds the ability to generate a random numeric key OR an alpha numeric key. To generate numeric, simply add the second paramater as true.

    Example Usage

    $randomNumber = izrand(32, true); // generates 32 digit number as string $randomAlphaNumeric = izrand(); // generates 32 digit alpha numeric string

    Typecast to Integer

    If you want to typecast the number to integer, simply do this after you generate the number. NOTE: This will drop any leading zeros if they exist.

    $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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line