Regular Expression for Single Letter – PHP

October 14, 2009DavidPHP0

I was working on a project where I needed to validate a querystring for a single letter — uppercase or lowercase. Since there is no php equivalent to the is_numeric() function, (e.g. a hypothetical is_alpha() function) I decided to use regular expressions to get the task done. I could have used ctype_alpha(), but that function wouldn’t account for the fact that I needed to find out if it’s a letter, AND if it’s a single character. I could have run two tests, but it was too much code and too many “if/else” statements. That’s why I went with RegExp.

I wanted to make sure that 1) there was only one character in the querystring, and 2) that the character was a letter — uppercase or lowercase.

Here’s the regular expression pattern  I used:

$pattern = '/^[A-Za-z]{1}$/';

I used the following function to test the pattern, where $variable is the queryString that is passed from the calling page.  The “good” and “not good” output text are for diagnostic use and of course, will be removed later on.

function letterCheck($variable) {
$pattern = '/^[A-Za-z]{1}$/';
if (preg_match($pattern, $variable)) {
echo "RegExp is good";
return 1;

else {
echo "RegExp is not good. " . $variable . " does not match the criteria. ";
return 0;

That’s it.


Related Posts

| More

SpiderOak Online Backup, Storage, Access, Sync, and Sharing

We are currently offering a free copy of our 16-page eBook, "How to Organize your Digital Photography Collection" to everyone who signs up for our free newsletter. This eBook will review how to organize your digital photos, discuss metadata, and give you an overview of software than can help you with your digital photography workflow. Sign up in the signup area, located in the right-side column of every page on this site, and read your copy now!