Friday, March 27, 2009

PHP ctype extension for data validation

PHP's ctype extension includes a set of functions which are wrappers around C's isDATATYPE functions (such as isalpha) that check whether a particular character is within a certain range. But unlike the C functions that only work on one character at a time, the PHP functions operate on the entire string. These functions are much faster than PHP's regular expression functions which are often used to validate input. As an example of where you might use these functions, suppose you have a string which is required to consist of all digits. Using regular expressions you might use

preg_match("/[0-9]+/", $somevar)

But using the ctype functions you could write it as

ctype_digit($somevar)

which is much faster.

No comments:

Post a Comment