Last Updated: February 25, 2016
·
1.642K
· masquerade

Use ctype instead of regex if possible

A lot of PHP scripts tend to rely on regular expression to validate user input.

While validating user input is a good idea and a must, doing so via regular expression can be quite slow.

In many cases the process of validation merely involves checking the source string against a certain character list such as A-Z or 0-9, etc...

Instead of using regex you can in many instances use the ctype extension to do the same. The ctype extension offers a series of function wrappers around C's is*() functions that check whether a particular character is within a certain range. Unlike the C functions that can only work a character at a time, PHP's functions can operate on entire strings and are a lot faster than equivalent regular expressions.

ctype_digit($foo);  
// is better than  
preg_match("![0-9]+!", $foo);

It can also be a good idea sometimes to use a narrow ctype check to check a string and if it passes then there is no need to run the broader regex. This way you will only run the regex when there is doubt about the input.

For more details on the ctype functions see the PHP manual.

http://www.php.net/manual/en/ref.ctype.php