user3524209
user3524209

Reputation: 111

RegEx for swiss phone number

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!

Upvotes: 11

Views: 14096

Answers (5)

ParrapbanzZ
ParrapbanzZ

Reputation: 370

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.

Upvotes: 11

Nadjib Khelifati
Nadjib Khelifati

Reputation: 559

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)

Upvotes: 1

webman
webman

Reputation: 1203

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

Upvotes: 2

Guns
Guns

Reputation: 2728

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})

Upvotes: 2

sshashank124
sshashank124

Reputation: 32199

You can do it as:

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

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

Upvotes: 3

Related Questions