How to check if a string has only uppercase letters?

Asked

Viewed 2,493 times

14

How can I check whether all the characters in a string are capital letters?

Preferably without the use of regular expressions.

  • 1

    Why would you like to do that? Wouldn’t it be better to either restrict the input or force uppercase letters?

  • 1

    Only uppercase letters? Numbers and spaces are allowed?

  • 1

    @Begnini In the specific case, only uppercase letters.

3 answers

23


For this you can use the function ctype_upper.

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

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

If it is necessary to allow numbers, spaces and symbols in general, you can use this alternative, which uses the function mb_strtoupper:

mb_strtoupper( $string1 ) === $string1;
  • 3

    mb_strtoupper only when compiled with mbstring support, 99% of the cases, but worth noting

  • @Exact Ernandes, you can use strtoupper, but then special characters would cause problems.

13

$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";  
}

4

There is yet another way, which is to compare whether the string is equal to 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";
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.