douoyou3348 2015-02-06 10:10
浏览 31
已采纳

剥离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?

  • 写回答

3条回答 默认 最新

  • dongwoqin7034 2015-02-06 10:38
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装
  • ¥40 复杂的限制性的商函数处理