PHP: Check if A String Contain Only Uppercase / Capital Letters

by Yang Yang on January 20, 2012

Sometimes you would want to check if a string is an acronym or an abbreviation by testing if it only contains capitalized letters from A to Z and nothing else. There are 2 ways to accomplish this simple task in PHP.

ctype_upper()

Use the native ctype_upper() function and you will know if the provided string contains only uppercase letters:

if (ctype_upper($string)) {
	echo $string.' is all uppercase letters.';
} else {
	echo $string.' is not all uppercase letters.';
}

The Ctype functions would turn out to be very handy when you want to test a string against different character types – digits, alphabetic, alpha-numeric, lowercase letters, uppercase letter, and even punctuations, etc. See the full list here: http://www.php.net/manual/en/ref.ctype.php

strtoupper()

Use the strtoupper() function to transform the string into all uppercase characters that’s capitalized letters, and then compare the transformed string against the original one to see if they are identical. If they are, then you are pretty sure the original string was also a string consisting of ONLY capital letters.

if (strtoupper($string) == $string) {
	echo $string.' is all uppercase letters.';
}

Check if A String Consists of Only Lowercase Letters

The same goes true if you want to do the test other way around. Just use ctype_lower() and strtolower() instead.

Comments on this entry are closed.

Previous post:

Next post: