doupinge9055 2013-04-16 21:18 采纳率: 100%
浏览 134
已采纳

用于密码字段验证的正则表达式[重复]

This question already has an answer here:

Sorry to all if this code is poor as I am just following through a book to and modifying it for my school project as I just started php less than a month ago.

I am trying to understand what this validation mean but can't seem to comprehend it full as I am new with php.

Code:

if (preg_match ('/^(\w*(?=\w*\d)(?=\w*[a-z])(?=\w*[A-Z])\w*){6,20}$/', $_POST['pass']) ) {

        //$p = mysqli_real_escape_string ($dbc, $_POST['pass']);
        $p = $_POST['pass'];
        $sticky_password = $p;

        } else {
        $error['pass'] = 'Please enter a valid password!';
        }

Any help would be really appreciated! Thanks!

Thank you very much.. :)

</div>
  • 写回答

2条回答 默认 最新

  • du060334 2013-04-16 22:59
    关注

    We have the following regex: /^(\w*(?=\w*\d)(?=\w*[a-z])(?=\w*[A-Z])\w*){6,20}$/

    1. The first and last / are the delimiters.

    2. ^ -> The start, $ -> The end

      Which means if input is abc and your regex is /^bc$/, it won't get matched since bc is not at the beginning.

    3. Now we have (\w*(?=\w*\d)(?=\w*[a-z])(?=\w*[A-Z])\w*){6,20}

      The {6,20} is the quantifier part, which means 6 up to 20 times.

    4. Let's break the regex further: \w*(?=\w*\d)(?=\w*[a-z])(?=\w*[A-Z])\w*

      Let's provide some equivalents:

      1. \w => [a-zA-Z0-9_]
      2. \d => [0-9]
      3. * => zero or more times
      4. (?=) Is a lookahead assertion. Example /a(?=b)/ this will match any "a" followed by "b"

      5. The purpose of those lookaheads:

        • (?=\w*\d) => check if there is a digit
        • (?=\w*[a-z]) => check if there is a lowercase letter
        • (?=\w*[A-Z]) => check if there is a uppercase letter
        • Let's take (?=\w*\d): The \w* is just there as a "workaround" in case there is [a-zA-Z0-9_]* before a digit

    In the end, this regex just makes sure that the input:

    1. is 6 to 20 characters long
    2. that there is minimal: 1 lowercase, 1 uppercase and 1 digit
    3. that the allowed characters are letters (upper and lowercase (a-z,A-Z)), digits and underscore.

    Three interesting sites www.regexper.com, www.regular-expressions.info and www.regex101.com.

    Note: Don't restrict passwords, you have to hash them anyway. Take a look here or check the other questions on SO.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!