tags:

views:

134

answers:

5

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

+18  A: 

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)
Matthew Scharley
+3  A: 
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.

karim79
+7  A: 

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.

PatrikAkerstrand
Only issue I have with the multibyte version is the encoding detection, which is a notoriously difficult thing to do, and will mangle your string if it gets it wrong. +1 for the only real way to do it though.
Matthew Scharley
Agreed. Added a little comment for that case
PatrikAkerstrand
+3  A: 

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

chris
the only correct answer!
stereofrog
A: 

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.

DancesWithBamboo