zoukankan      html  css  js  c++  java
  • PHP实现密码生成器包含大小写字母数字特殊字符

    function createPassword($length = 16)
    {
        $pwd = '';
        $num = 0;
        $str = "~!@#$%^&*_-+=`|\(){}[]:;\"'>,.?/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        $count = strlen($str);
        while ((strlen($pwd) < $length) || $num < $length) {
            $rand = rand(0, $count);
            $sub = substr($str, $rand, 1);
            $pwd .= $sub;  //此处去除< 小于号,
            $num++;
            echo $pwd . '  自增值: ' . $num . '  随机字符位置: ' . $rand . '<br>';
        }
        return $pwd;
    }
    
    $createPwd = createPassword(32);
    echo '密码: ' . $createPwd;
    echo '<br>';
    echo "密码长度: " . strlen($createPwd);
    die;

    效果图;

    但不知道为什莫,字符串中不能带< 小于号,有时间再研究下,有大佬知道的可以给指点指点.

    解答:首先感谢大佬,在百忙之中,为小弟解惑

    这个问题简单易懂,但是你不真实操作下,往往容易忽略掉

    附上大佬给优化后的代码:

    function createPassword($length = 16)
    {
        $pwd = '';
        $num = 0;
        $str = "<~!@#$%^&*_-+=`|\(){}[]:;\"'>,.?/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        $count = strlen($str);
        for($i = 0; $i < $length; $i++){
            $rand = rand(0, $count-1);
            $pwd .= $str[$rand];
            echo $pwd . '  自增值: ' . $num . '  随机字符位置: ' . $rand . '<br>';
        }
        return $pwd;
    }
    
    $createPwd = createPassword(32);
    echo '密码: ' . $createPwd;
    echo '<br>';
    echo "密码长度: " . strlen($createPwd);
    die;

    所以,要求不高的情况下,可以把< 去掉,或者在命令行直接操作就好.

    赞赏码

    非学,无以致疑;非问,无以广识

  • 相关阅读:
    LeetCode 382. Linked List Random Node
    LeetCode 398. Random Pick Index
    LeetCode 1002. Find Common Characters
    LeetCode 498. Diagonal Traverse
    LeetCode 825. Friends Of Appropriate Ages
    LeetCode 824. Goat Latin
    LeetCode 896. Monotonic Array
    LeetCode 987. Vertical Order Traversal of a Binary Tree
    LeetCode 689. Maximum Sum of 3 Non-Overlapping Subarrays
    LeetCode 636. Exclusive Time of Functions
  • 原文地址:https://www.cnblogs.com/lxwphp/p/15452619.html
Copyright © 2011-2022 走看看