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

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧