February 18, 2008
The Power of Regular Expressions
Regular expressions can be somewhat daunting to the beginning programmer. They really do look scary. But just like the back of your math book, it feels pretty good to look back and realize how far you’ve come. I’m going to give you an example of the power of regular expressions, and this really only glosses over the surface of them. If you can master regular expressions, this will seriously save you many lines of code, and a lot of grief. Take a look at the following two examples of validating a number in PHP:
If you are somewhat unstable you would attempt to validate your number with a series of if / else structures testing for each precise property that your number must have.
//our number to check
$number = "654321-00";
//number should be 9 characters long
if (strlen($number) == 9) {
//3rd to last character should be "-"
if (substr($number, -3, 1) == "-") {
//first 6 characters must be numeric
if (is_numeric(substr($number, 0, 6))) {
//last 2 characters must be numeric or alpha
if (is_numeric(substr($number, -2, 2)) ||
is_string(substr($number, -2, 2))) {
echo "Your value " . $number . " is valid";
} else {
echo "wrong value";
}
} else {
echo "wrong value";
}
} else {
echo "wrong value";
}
} else {
echo "wrong value";
}
Not only is the regular expression shorter and cleaner, it is also much more precise in defining exactly what you want:
$number = "654321-00"; //our number to check
$pattern = "/^[\d]{6}[\-]{1}[\w]{2}$/"; //the regex pattern
if (preg_match($pattern, $number) {
echo "Your value " . $number . " is valid";
} else {
echo "wrong value";
}
