剥离Phonenumber(移动)

Is there a function or a easy way to strip down phone numbers to a specific format?

Input can be a number (mobile, different country codes)

maybe

+4917112345678
+49171/12345678
0049171 12345678

or maybe from another country

004312345678
+44...

Im doing a

$mobile_new = preg_replace("/[^0-9]/","",$mobile);  

to kill everything else than a number, because i need it in the format 49171 (without + or 00 at the beginning), but i need to handle if a 00 is inserted first or maybe someone uses +49(0)171 or or inputs a 0171 (needs to be 49171.

so the first numbers ALWAYS need to be countryside without +/00 and without any (0) between.

can someone give me an advice on how to solve this?

You can use

(?:^(?:00|\+|\+\d{2}))|\/|\s|\(\d\)

to match most of your cases and simply replace them with nothing. For example:

$mobile = "+4917112345678";
$mobile_new = preg_replace("/(?:^(?:00|\+|\+\d{2}))|\/|\s|\(\d\)/","",$mobile);
echo $mobile_new;
//output: 4917112345678

regex101 Demo

Explanation:

I'm making use of OR here, matching each of your cases one by one:

  1. (?:^(?:00|\+|\+\d{2})) matches 00, + or + followed by two numbers at the beginning of your string
  2. \/ matches a / anywhere in the string
  3. \s matches a whitspace anywhere in the string (it matches the newline in the regex101 demo, but I suppose you match each number on its own)
  4. \(\d\) matches a number enclosed in brackets anywhere in the string

The only case not covered by this regex is the input format 01712345678, as you can only take a guess what the country specific prefix can be. If you want it to be 49 by default, then simply replace each input starting with a single 0 with the 49:

$mobile = "01712345678";
$mobile_new = preg_replace("/^0/","49",$mobile);
echo $mobile_new;
//output: 491712345678

This pattern (49)\(?([0-9]{3})[\)\s\/]?([0-9]{8}) will split number in three groups:

  • 49 - country code
  • 3 digits - area code
  • 8 digits - number

After match you can construct clean number just concatnating them by \1\2\3.

Demo: https://regex101.com/r/tE5iY3/1

If this not suits you then please explain more precisely what you want with test input and expected output.

I recommend taking a look at LibPhoneNumber by Google and its port for PHP. It has support for many formats and countries and is well-maintained. Better not to figure this out yourself.

https://github.com/giggsey/libphonenumber-for-php

$phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
$usNumberProto = $phoneUtil->parse("+1 650 253 0000", "US");