简体   繁体   中英

PHP regular expression to check string contains upper and lowercase letters

What is the simplest regular expression that will check if a string contains at least one uppercase letter and one lowercase?

Edit: This is for a password where there may be numeric characters present as well, so the uppercase and lowercase chars might not be next to each other.

I suspect you mean "ASCII character".

  • Simple: [AZ].*[az]|[az].*[AZ]
  • Elegant: ^(?=.*?[AZ])(?=.*?[az])

The "simple" variant just checks for the two possibilities: Either the uppercase character comes before the lowercase, or it's the other way around.

The "elegant" variant uses two positive look-ahead assertions to scan the string without actually moving the regex engine forward or matching anything.

In contrast to the first method, this variant is very easily extendable for more checks and it allows you to consume the string after you checked that it meets your requirements.

Checking for both upper and lower case in a string can also be accomplished without a regular expression.

The code for this would look like the following:

$word = 'AA1FAa';

// Check if word has both uppercase and lowercase letters
if(strtolower($word) != $word && strtoupper($word) != $word){
    echo 'Has both upper and lower case letters';
}else{
    echo 'Does not have both upper and lower case letters';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM