PHP:如何知道字符串中的所有字母都是大写?

发布于 2024-08-24 07:18:51 字数 25 浏览 5 评论 0原文

如何知道字符串中的所有字母都是大写?

How to know that all letters in a string are upper case?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

︶ ̄淡然 2024-08-31 07:18:51

您可以使用 strtoupper 将字符串转换为大写。现在您知道它是大写的,您可以检查原始字符串是否与它匹配。

IE。

$str === strtoupper($str)

You can use strtoupper to convert your string to uppercase. You now know that it is uppercase, and you can check if the original string matches it.

ie.

$str === strtoupper($str)
爱你是孤单的心事 2024-08-31 07:18:51

您可以尝试制作字符串的副本,将副本转换为大写,然后将其与原始字符串进行比较:

public function isUpperCase ($string) {
   return $string === strtoupper($str);
}

或者,更好的版本(多字节安全*)将是:

public function mb_isUpperCase ($string) {
   $upper = mb_convert_case( 
      $string, 
      MB_CASE_UPPER, 
      mb_detect_encoding( 
         $string
      )
   );
   return $string === $upper;
}

*注意 mb_detect_encoding 可能会失败,并返回 false。在生产环境中,您应该向 mb_detect_encoding 提供可能的编码列表,或处理 mb_detect_encoding 的情况失败。

You could try making a copy of the string, convert the copy to upper case, and compare it to the original string:

public function isUpperCase ($string) {
   return $string === strtoupper($str);
}

OR, a better version (which is multibyte-safe*) would be:

public function mb_isUpperCase ($string) {
   $upper = mb_convert_case( 
      $string, 
      MB_CASE_UPPER, 
      mb_detect_encoding( 
         $string
      )
   );
   return $string === $upper;
}

*Note that mb_detect_encoding can fail, and return false. In a production environment you should either provide a list of possible encodings to mb_detect_encoding, or handle the case where mb_detect_encoding fails.

昨迟人 2024-08-31 07:18:51
if(strcmp(strtoupper($str), $str) === 0) {
    echo 'is uppercase';
}

使用 mb_strtoupper ,其中特殊字符涉及编码。

使用 strcmp 进行二进制安全字符串比较。

if(strcmp(strtoupper($str), $str) === 0) {
    echo 'is uppercase';
}

Use mb_strtoupper where special character encodings are involved.

Use strcmp for binary-safe string comparison.

骄傲 2024-08-31 07:18:51

如果所有字符都是字母,并且它是一个 ascii 字符串,则 ctype_upper() 可能是一种可能性。

ctype_upper() might be a possibility if all the characters are letters, and it's an ascii string.

静水深流 2024-08-31 07:18:51

如果它是一个很长的字符串并且您不想制作副本,则遍历该字符串并查看每个字符的 ascii 值。如果它小于 97,则说明它全部是大写。

If its a long string and you don't want to make a copy then walk the string and look at each character's ascii value. If it is less than 97 you know it is all uppercase.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文