Formatting Phone Number and Fixing User Input With PHP

Recently I was writing a franchise module for a shopping cart software that required franchise owners to input their phone number.  I’ve ran into the problem where no matter what instructions I’ve given, the franchise owners consistently like to format the phone number in their own unique way.  Rather than add 3 text boxes to where they have to tab between every part of the phone number, I wrote a quick and easy php script to handle all the leg work for me!

[php]
//Input example
//(999)999.9999
//Output examples
//formatPhoneNum($phone_number, 1) outputs (999) 999-9999
// Inputting 999-9999 would cause the function to return “False”
function formatPhoneNum($phone_number, $style){
// Style 1 – (999) 999-9999
// Style 2 – 999-999-9999
// Style 3 – 999.999.9999
// Style 4 – 9999999999
$number = str_replace(array(‘(‘, ‘)’, ‘-‘, ‘ ‘), ”, $phone_number);
if (strlen($number) == 10){
$area = substr($number, 0, 3);
$first = substr($number, 3, 3);
$last = substr($number, 6);

switch($style){
case 1:
return “($area) $first-$last”;
case 2:
return “$area-$first-$last”;
case 3:
return “$area.$first.$last”;
case 4:
return “$area$first$last”;
}
// if the phone number was too long or too short
else {
return false;
}
}
[/php]