Created
April 5, 2012 22:36
-
-
Save muratpurc/2314727 to your computer and use it in GitHub Desktop.
PHP: Regex to validate different phone number formats
This file contains 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 | |
/** | |
* Regular expression to validate different types of phone numbers | |
*/ | |
// simple pattern | |
$pattern = '/^[0-9\-\(\)\/\+\s]*$/'; | |
// example phone numbers | |
$phoneNumbers = ' | |
0821 12 34 567 | |
08211234567 | |
0821-1234567 | |
0821-12 34 567 | |
0821 - 1234567 | |
0821 - 12 34 567 | |
0821/1234567 | |
0821/12 34 567 | |
0821 / 1234567 | |
0821 / 12 34 56 7 | |
+49(821) 1234-567 | |
+49 (821) 12 34 - 567 | |
'; | |
// convert the examples to an array | |
$phoneNumbers = explode("\n", trim($phoneNumbers)); | |
// loop thru them and run preg_match for each number. | |
// the variable $matches should contain the number in case of a successful validation. | |
foreach ($phoneNumbers as $number) { | |
preg_match($pattern, $number, $matches); | |
echo '<pre>Number: ' . $number . "\n" | |
. 'Match: ' . print_r($matches, true) . '</pre>'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It s not working!