bill williams
bill williams

Reputation: 1

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

I found lots of php regex and other options to determine string length, and if it contains one letter or one number, but how do I determine if a string has 2 numbers in it?

I am trying to validate a password that

Is there a one line regex solution for this?

Upvotes: 0

Views: 2340

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

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

(?=...) is a lookahead assertion. It checks if a certain regex can be matched at the current position, but doesn't actually consume any part of the string, so you can just place several of those in a row.

Upvotes: 7

Related Questions