There may be times when you need a way to check that a string only contains alpha-numeric characters. That means only alphabets A-Z and numbers 0-9.

Most PHP-ers will probably use regular expressions and the function preg_match(). I will admit that regular expressions is really powerful, but it’s a real pain to learn and master. Fortunately PHP provides another function you can use.

Check out ctype_alnum() function.

ctype_alnum($text) will return true if $text is a mix of alphabets, numbers or both. Here’s how you can use it:

Also, if you just want to look for purely alphabets, you can use the ctype_alpha(), and conversely, if you want to look for purely numbers in the string, you can use ctype_digit().

There is another function which does the same thing as ctype_digit, and that is is_numeric().

However, a better function to use in place of ctype_digit, might be is_numeric(). This example illustrates why:

ctype_digit purely checks for string types, whereas is_numeric takes in multiple types of variables, such as integers, floats and strings and tries to evaluate it to have a numerical value.