Search code examples
phpregexreplacepreg-replacestripping

Stripping down Phonenumber (mobile)


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?


Solution

  • 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