Created
March 20, 2014 17:17
-
-
Save RadGH/9669034 to your computer and use it in GitHub Desktop.
This function quickly grabs the 10 digit phone number from a string, formatted as (xxx) xxx-xxxx.
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
| <?php | |
| // This function quickly grabs the 10 digit phone number from a string. | |
| // Works with most user input. | |
| // Standard US phone number format only. | |
| // Note: For storage, always store what the user gives you (ex: 555-123-1234 until 5pm, after that call 555-123-1234) | |
| function extract10digitphone( $str, $format = '(%s) %s-%s' ) { | |
| $regex = '/([0-9]{3}).*([0-9]{3}).*([0-9]{4})/mU'; | |
| if ( preg_match( $regex, $str, $match ) ) { | |
| return sprintf( $format, $match[1], $match[2], $match[3] ); | |
| } | |
| return false; | |
| } | |
| // Example usage. Some of these are *expected* to fail | |
| $test_cases = explode("\n", "(+351) 282 43 50 50 | |
| 90191919908 | |
| 555-8909 | |
| 001 6867684 | |
| 001 6867684x1 | |
| 1 (234) 567-8901 | |
| 1-234-567-8901 x1234 | |
| 1-234-567-8901 ext1234 | |
| 1-234 567.89/01 ext.1234 | |
| 1(234)5678901x1234 | |
| (123)8575973 | |
| (0055)(123)8575973 | |
| 1-234-567-8901 | |
| 1-234-567-8901 x1234 | |
| 1-234-567-8901 ext1234 | |
| 1 (234) 567-8901 | |
| 1.234.567.8901 | |
| 1/234/567/8901 | |
| 12345678901"); | |
| echo '<pre>'; | |
| foreach( $test_cases as $phone ) { | |
| $formatted = extract10digitphone( $phone ); | |
| echo $phone . "\n" . ($formatted ?: '[false]') . "\n\n"; | |
| } | |
| echo '</pre>'; | |
| /* | |
| Output: | |
| (+351) 282 43 50 50 | |
| [false] | |
| 90191919908 | |
| (901) 919 - 1990 | |
| 555-8909 | |
| [false] | |
| 001 6867684 | |
| (001) 686 - 7684 | |
| 001 6867684x1 | |
| (001) 686 - 7684 | |
| 1 (234) 567-8901 | |
| (234) 567 - 8901 | |
| 1-234-567-8901 x1234 | |
| (234) 567 - 8901 | |
| 1-234-567-8901 ext1234 | |
| (234) 567 - 8901 | |
| 1-234 567.89/01 ext.1234 | |
| (234) 567 - 1234 | |
| 1(234)5678901x1234 | |
| (234) 567 - 8901 | |
| (123)8575973 | |
| (123) 857 - 5973 | |
| (0055)(123)8575973 | |
| (005) 123 - 8575 | |
| 1-234-567-8901 | |
| (234) 567 - 8901 | |
| 1-234-567-8901 x1234 | |
| (234) 567 - 8901 | |
| 1-234-567-8901 ext1234 | |
| (234) 567 - 8901 | |
| 1 (234) 567-8901 | |
| (234) 567 - 8901 | |
| 1.234.567.8901 | |
| (234) 567 - 8901 | |
| 1/234/567/8901 | |
| (234) 567 - 8901 | |
| 12345678901 | |
| (123) 456 - 7890 | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment