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:

ctype_alnum()

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

ctype_alpha()

matches A-Z, a-z

ctype_cntrl()

matches ASCII control characters

ctype_digit()

matches 0-9

ctype_graph()

matches values that can be represented graphically

ctype_lower()

matches a-z

ctype_print()

matches visible characters (not whitespace)

ctype_punct()

matches all non-alphanumeric characters (not whitespace)

ctype_space()

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

ctype_upper()

matches A-Z

ctype_xdigit()

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:

<?php
    $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().

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

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.