Mastering Regular Expressions in PHP
(Page 3 out of 4)Another great example would be a telephone number. Say you want to verify telephone numbers and make sure they were in the correct format. Let's assume you want the numbers to be in the format of xxx-xxxxxxx. The code would look something like this:
// Good number
$good = "123-4567890";
// Bad number
$bad = "45-3423423";
// Let's check the good number
if (preg_match("/\d{3}-\d{7}/", $good)) {
echo "Valid number";
} else {
echo "Invalid number";
}
echo '';
// And check the bad number
if (preg_match("/\d{3}-\d{7}/", $bad)) {
echo "Valid number";
} else {
echo "Invalid number";
}
?>
The regex is fairly simple, because we use \d. This basically means "match any digit" with the length behind it. In this example it first looks for 3 digits, then a '-' (hyphen) and finally 7 digits. Works perfectly, and does exactly what we want.