Regular Expression for Single Letter – PHP

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:

[php]$pattern = ‘/^[A-Za-z]{1}$/’;[/php]

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.

[php]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;
}
}[/php]

That’s it.

Click Me