dqj5046 2012-08-08 16:36
浏览 35
已采纳

此RegEx仅适用于8位数的电话号码,如何使其适用于15位数?

Someone in Stack Overflow gave me this code:

$output = preg_replace( '/(\+?\d{2}|0)(\d{7,8})/', '0$2', $test);

It changes user input:

+622112345 into 02112345

622112345 into 02112345

02112345 into 02112345

Unfortunately it only works for 7-8 digits. I decided to change the code into this:

$output = preg_replace( '/(\+?\d{2}|0)(\d{15})/', '0$2', $test);

By changing (\d{7,8}) into (\d{15}), I hoped I could get this RegEx to validate up to 15 digits. But, here's what I have:

input : 083812345678910 >> output : 083812345678910 [correct]

input : 6283812345678910 >> output : 6283812345678910 [false, should be : 083812345678910]

input : +6283812345678910 >> output : 6283812345678910 [false, should be : 083812345678910]

How can I make this works on 15 digit numbers? Thanks.

UPDATE : user input can be 10, 11, 12 or even 13 digits. but not more than 15 digits. so I need this code to change the prefix : either +62, 62 or 0 INTO 0xxxx. no matter how many digits they have, 15 maximum.

  • 写回答

1条回答 默认 最新

  • dongmei3869 2012-08-08 16:43
    关注

    The correct regex is:

    $output = preg_replace( '/(0|\+?\d{2})(\d{7,14})/', '0$2', $test);
    

    Even though you have 16 digit numbers, there should only be at most 14 digits after the extension, to account for the 2 digit extension. Note that this will work for more extensions other than 62, if this is not desired, replace \d{2} with 62.

    Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息