Skip to content

Instantly share code, notes, and snippets.

@muratpurc
Created April 5, 2012 22:36
Show Gist options
  • Save muratpurc/2314727 to your computer and use it in GitHub Desktop.
Save muratpurc/2314727 to your computer and use it in GitHub Desktop.
PHP: Regex to validate different phone number formats
<?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>';
}
@Pronik2009
Copy link

TY

@vinothkbest
Copy link

It s not working!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment