开发者

PHP regular expression to check string contains upper and lowercase letters

开发者 https://www.devze.com 2023-03-22 19:19 出处:网络
What is the simplest regular expression that will check if a string contains at leas开发者_开发问答t one uppercase letter and one lowercase?

What is the simplest regular expression that will check if a string contains at leas开发者_开发问答t 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: [A-Z].*[a-z]|[a-z].*[A-Z]
  • Elegant: ^(?=.*?[A-Z])(?=.*?[a-z])

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';
}
0

精彩评论

暂无评论...
验证码 换一张
取 消