You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除手机号中的+27并格式化,兼容两种输入场景

解决方案

修改后的代码可同时处理带+27前缀和不带前缀的南非手机号,核心逻辑是先移除南非国家码(若存在),再执行格式化:

<!DOCTYPE html>
<html>
<head>
  <title>Phone Number Format</title>
</head>
<body>
   <form action="" method="POST">
     <input type="text" name="phone" id="phone" placeholder="Enter phone number">
     <input type="submit" value="Submit">
  </form>
<?php
   if(isset($_POST['phone'])) {
    $phoneNumber = $_POST['phone'];
    // 移除所有非数字字符
    $phoneNumber = preg_replace('/\D/', '', $phoneNumber);
    
    // 检查是否包含南非国家码27,若有则移除
    if (str_starts_with($phoneNumber, '27')) {
        $phoneNumber = substr($phoneNumber, 2);
    }
    
    // 格式化手机号(确保剩余9位有效数字)
    if (strlen($phoneNumber) === 9) {
        $formatNumber = "(" . substr($phoneNumber, 0, 3) . ") " . substr($phoneNumber, 3, 3) . "-" . substr($phoneNumber, 6);
        echo "phone number: " . $formatNumber;
    } else {
        echo "Invalid phone number format";
    }
  }
 ?>

 </body>
</html>

关键修改说明

  • 移除国家码:用str_starts_with判断纯数字字符串是否以27开头(对应输入的+27),若是则截取从第3位开始的子串,得到去掉国家码的9位手机号。
  • 合法性校验:添加长度检查,确保处理后的数字为9位,避免非法输入导致格式化错误。
  • 兼容原有逻辑:不带国家码的输入(如0608797221)会直接进入格式化步骤,保留原有功能。

内容的提问来源于stack exchange,提问作者Nick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 09:22:13