Created
August 1, 2017 15:54
-
-
Save prajwal-stha/bf2140a332d110a2d7d3347d3b378784 to your computer and use it in GitHub Desktop.
Format phone number in US format
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 = '2142234736'; | |
| $phone = format_phone_us( $phone); | |
| echo $phone; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment