14
How can I check whether all the characters in a string
are capital letters?
Preferably without the use of regular expressions.
14
How can I check whether all the characters in a string
are capital letters?
Preferably without the use of regular expressions.
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;
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 php string
You are not signed in. Login or sign up in order to post.
Why would you like to do that? Wouldn’t it be better to either restrict the input or force uppercase letters?
– Daniel T. Sobrosa
Only uppercase letters? Numbers and spaces are allowed?
– Begnini
@Begnini In the specific case, only uppercase letters.
– jonathancardoso