How to check if a string has only uppercase letters?

13

How can I check if all characters in a string are uppercase?

Preferably, without the use of regular expressions.

    
asked by anonymous 11.12.2013 / 17:33

3 answers

22

For this you can use the ctype_upper function.

$string1 = 'ALLCAPS';
$string2 = 'NotAlLCAPS';

var_dump( ctype_upper( $string1 ), ctype_upper( $string2 ) );
//bool(true)
//bool(false)

If you need to allow numbers, spaces and symbols in general, you can use this alternative, which uses mb_strtoupper :

mb_strtoupper( $string1 ) === $string1;
    
11.12.2013 / 17:33
12
$string    = "ABCDE";  
$uppercase = preg_match('#^[A-Z]+$#', $string);  

or

$string   = "ABCDE";
if (ctype_upper($string)) // retorna true se toda string estiver em maiúscula  
{  
    echo "A string $string está toda em maiúscula";  
}
    
16.12.2013 / 15:07
3

There is yet another way, which is to compare if the string is equal itself in the call of strtoupper .

$upper = 'TUDO UPPER';

$non_upper = 'Nem Tudo UPPER';


if (strtoupper($upper) === $upper) {
    echo "Sim, é tudo maiúscula";
}

if (strtoupper($non_upper) !== $non_upper) {
     echo "Não é tudo maiúscula";
}
    
16.05.2016 / 22:15