Advanced variable validation using CTYPE

For more specific parsing of character types in a variable, the CTYPE library is available. If you want to check for particular values inside a variable, and want to do so very fast, CTYPE is for you. Compared to a test like is_numeric(), the equivalent CTYPE check is about three times faster. There are eleven CTYPE functions in total, all of which work in the same way as is_numeric(): you pass a variable in, and get either true or false back.

The eleven prototypes are:

bool ctype_alnum ( string text)

bool ctype_alpha ( string text)

bool ctype_cntrl ( string text)

bool ctype_digit ( string text)

bool ctype_graph ( string text)

bool ctype_lower ( string text)

bool ctype_print ( string text)

bool ctype_punct ( string text)

bool ctype_space ( string text)

bool ctype_upper ( string text)

bool ctype_xdigit ( string text)

Each of these match different text types, and this table briefly categorises what each function matches:


matches A-Z, a-z, 0-9


matches A-Z, a-z


matches ASCII control characters


matches 0-9


matches values that can be represented graphically


matches a-z


matches visible characters (not whitespace)


matches all non-alphanumeric characters (not whitespace)


matches whitespace (space, tab, new line, etc)


matches A-Z


matches digits in hexadecimal format

The matches are absolute, which means that ctype_digit() will return false for the value "123456789a" because of the "a" at the end, as this script shows:

    $var = "123456789a";
    print (int)ctype_digit($var);

Also note that there is no match for floating-point numbers available, as ctype_digit() matches 0-9 without also matching the decimal point. As a result, it will return false for 123.456. For this purpose you need to use is_float().


If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Key validation points >>

Previous chapter: Validation in practice

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.