简体   繁体   English

PHP 正则表达式检查字符串是否包含大小写字母

[英]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".我怀疑你的意思是“ASCII 字符”。

  • Simple: [AZ].*[az]|[az].*[AZ]简单: [AZ].*[az]|[az].*[AZ]
  • Elegant: ^(?=.*?[AZ])(?=.*?[az])优雅: ^(?=.*?[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';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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