PHP 检查字符串是否有 2 个数字、8 个字符和 1 个大写字母


PHP check that string has 2 numbers, 8 chars and 1 capital

我找到了很多php正则表达式和其他选项来确定字符串长度,以及它是否包含一个字母或一个数字,但是如何确定字符串中是否有2个数字?

我正在尝试验证一个密码

  • 必须正好包含 8 个字符

  • 其中一个必须是大写字母

  • 其中 2 个必须是数字

是否有单行正则表达式解决方案?

if (preg_match(
    '/^            # Start of string
    (?=.*'p{Lu})   # at least one uppercase letter
    (?=.*'d.*'d)   # at least two digits
    .{8}           # exactly 8 characters
    $              # End of string
    /xu',     
    $subject)) {
    # Successful match

(?=...)是一个前瞻性的断言。它检查某个正则表达式是否可以在当前位置匹配,但实际上并不消耗字符串的任何部分,因此您只需将其中几个放在一行中。