11

I need a RegEx to do the validation (using Laravel, a php framework) for a swiss phone number which has to fit this format:

+41 11 111 11 11

The "+41" part has to be exactly this way while the rest (11 111 11 11) can be any number between 1 and 9.

The function that invokes the RegEx looks like this:

    $regex = "thisIsWhereINeedYourHelp";

    if (preg_match($regex, $value)) {
               return true;
            } 
    return true;

Thanks for your help!

user3524209
  • 111
  • 1
  • 1
  • 3
  • 2
    Possible duplicate of http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation?rq=1 – Kryten Apr 11 '14 at 14:55

5 Answers5

9

This is the pattern I use:

/(\b(0041|0)|\B\+41)(\s?\(0\))?(\s)?[1-9]{2}(\s)?[0-9]{3}(\s)?[0-9]{2}(\s)?[0-9]{2}\b/

it matches all the following:

+41 11 111 11 11
+41 (0) 11 111 11 11
+41111111111
+41(0)111111111
00411111111
0041 11 111 11 11
0041 (0) 11 111 11 11
011 111 11 11
0111111111

any of the spaces can be left out and it checks for the word and non word boundaries.

ParrapbanzZ
  • 252
  • 2
  • 8
  • in case you only want to match numbers with country prefix, starting with 0041 or +41 `/(\b(0041)|\B\+41)(\s?\(0\))?(\s)?[1-9]{2}(\s)?[0-9]{3}(\s)?[0-9]{2}(\s)?[0-9]{2}\b/` – F.H. Dec 23 '20 at 17:19
  • This regex here works as opposed to the answer https://gist.github.com/peyerluk/8357036 – zyrup Nov 08 '22 at 07:08
3

You can do it as:

(\+41)\s(\d{2})\s(\d{3})\s(\d{2})\s(\d{2})

Demo: http://regex101.com/r/hJ9oY0

sshashank124
  • 31,495
  • 9
  • 67
  • 76
2

Here is a regex which would work fine with a Swiss Phone Number:

^(\+?)(\d{2,4})(\s?)(\-?)((\(0\))?)(\s?)(\d{2})(\s?)(\-?)(\d{3})(\s?)(\-?)(\d{2})(\s?)(\-?)(\d{2})
Guns
  • 2,678
  • 2
  • 23
  • 51
  • 3
    In Switzerland, we never write phone numbers with a hyphen, so you could actually omit every `(\-?)` in this regex – SimonS Oct 17 '18 at 11:38
2

I first cleanup the string a bit (that avoids useless matches):

// input string cleanup
$input = preg_replace('/[^0-9+\(\)-]/', '', $input);

I than match a swiss number:

// swiss telephone validation +41 (0)xx xxx xxxx
if(preg_match('/^(\+41|0041|0){1}(\(0\))?[0-9]{9}$/',$input))
        $result = "match: CH";
else    $result = "no match";

this should match all swiss formats and be fairly reliable

webman
  • 1,117
  • 15
  • 41
1

You can use Laravel-Phone package for Validation, Formatting and more functionality.

In your case you can specify you country like this :

'phone' => 'required|phone:CH'

CH = Switzerland (Confoederatio Helvetica)