Almost every PHP application, be it a Web form or a CLI
program, requires user input. And because users are notoriously fickle, it’s
important to check the data they enter for validity before using it for
anything important—for instance, a calculation or a database entry.
Fortunately, there’s a hidden jewel in the PHP toolkit that
can help with this task. It’s the PHP ctype extension, and it contains functions to test if a
value belongs to a particular character class—that is, whether it contains only
alphabetic characters, only numbers, only printable or special characters, or
combinations thereof.
This document outlines the more useful functions available
in this PHP extension, with explanations and usage examples. (Table A)
Table A
Function |
Explanation |
Example |
ctype_alpha($val) |
This function returns true if every character in the input Use this function for input that must contain alphabetic |
<?php // returns true echo ctype_alpha(“hello”) ? “true” : “false”; // returns false |
ctype_digit($val) |
This function returns true if every character in the input Use this function for input that must only contain Note: Decimal |
<?php // returns true echo ctype_digit(“5419520217”) ? “true” : “false”; // returns false |
ctype_alnum($val) |
This function returns true if every character in the input Note: White |
<?php // returns true echo ctype_alnum(“OX14HP”) ? “true” : “false”; // returns false |
ctype_space($val) |
This function returns true if every character in the input |
<?php // returns true echo ctype_space(” “) ? “true” : “false”; // returns false |
ctype_cntrl($val) |
This function returns true if every character in the input Note: White |
<?php // returns true echo ctype_cntrl(“\t”) ? “true” : “false”; // returns false |
ctype_punct($val) |
This function returns true if every character in the input |
<?php // returns true echo ctype_punct(“?;*&^%$#”) ? “true” : “false”; // returns false |
ctype_print($val) |
This function returns true if every character in the input |
<?php // returns true echo ctype_print(“abc&%$245 “) ? “true” : “false”; // returns false |
ctype_graph($val) |
This function returns true if every character in the input |
<?php // returns true echo ctype_graph(“abc&%$245”) ? “true” : “false”; // returns false |
ctype_upper($val)
and ctype_lower($val) |
These functions return true if every character in the |
<?php // returns true echo ctype_upper(“ABC”) ? “true” : “false”; // returns false // returns false |