Posts Tagged ‘practical’

Regular Expressions for input validation?

Saturday, June 28th, 2008

It is always a good idea to try and avoid regular expressions, where possible and practical. There are functions in PHP which will do exactly what some regular expressions do, but faster. Take this example:

if(ereg(’[0123456789]‘, $number)) {
// Is integer
}else{
// Is not integer
}

It is much faster to do this instead:

if(ctype_digit($number)) {
// Is integer
}else{
// Is not integer
}

To test this, I used ereg(’[0123456789]‘, $number) 1,000,000 times, followed by using ctype_digit($number) 1,000,000 times. Here are the results:

Regular Expressions: 2.401 seconds
ctype_digit: 0.985 seconds
Time saved: 1.416 seconds; 58.98%