7.7.4 Advanced variable validation using CTYPEThis is NOT the latest copy of this book; click here for the latest version.
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 see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|