PHP Example: preg_match() USA Telephone Number Matching

I’ve practiced about how to match USA telephone number format in different format using preg_match() function. The first time I found the exercise is in the Learning PHP 5 by David Sklar. In B8 exercise we have to write PHP script: regular expression that flexibly matches a U.S. phone number whether or not it has parentheses around the area code and has its parts separated by spaces, hyphens, or periods.

Of course, there is the answer for this exercise. But, when I tried, It didn’t smoothly solve the problem. The script wasn’t able to filter double parentheses like “((“, “))”, “(( )”, or “( ))”. So, I have a will to fix it and here the fixed script.

$telephone = array("((718)) 498-1043","((718) 498-1043","718)) 498-1043","((718 498-1043","718) 498-1043","(718 498-1043","(718) 498-1043","(718) 498 1043","718 498 1043","718 498-1043","718-498-1043","718.498.1043");
foreach($telephone as $key => $match){

      echo $key." => ".$match." = Match <br />";
    } else {
      echo $key." => ".$match." = Not match <br />";

You can use and modify the script freely. Please use it and learn about preg_match(), preg_replace(), and also about array() carefully.