- Michael Barton |
- Free Stuff, PHP, Web Development |
- August 18th, 2009
Been out of the game a little while, my apologies. I know there isn’t much I can do to make it up to you (my fans); however, I’ll give you this in hopes of trying to win you back.
Format phone function using PHP:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | function format_phone($country, $phone) { $function = 'format_phone_' . $country; if(function_exists($function)) { return $function($phone); } return $phone; } function format_phone_us($phone) { // note: making sure we have something if(!isset($phone{3})) { return ''; } // note: strip out everything but numbers $phone = preg_replace("/[^0-9]/", "", $phone); $length = strlen($phone); switch($length) { case 7: return preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $phone); break; case 10: return preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $phone); break; case 11: return preg_replace("/([0-9{1})([0-9]{3})([0-9]{3})([0-9]{4})/", "$1($2) $3-$4", $phone); break; default: return $phone; break; } } // usage $phone = '111 111 1111'; $phone = format_phone('us', $phone); echo $phone; |
You might be wondering why I have 2 functions in there, right? Well, here’s the thing. I like to make things resusable. That being said, I’m leaving the door open to use the same kind of interface, format_phone(‘us’, $phone) or format_phone(‘canada’, $phone), to format other types of phone numbers should the functions exists. I’ll leave those types of implementations as homework.
TODO: update this so that it’s a little bit more users friendly.
