在处理国际业务相关的用户手机号时,我们常遇到需要将国内手机号转换为国际格式的场景,比如国内手机号是13800138000,需要去掉首位的0,拼接上国家代码86,最终得到8613800138000。下面分别介绍在原生PHP和Laravel框架下的实现方式。

原生PHP实现方式
原生PHP可以通过字符串截取的方式快速处理手机号,核心是先判断手机号首位是否为0,再拼接国家代码。
基础实现代码
<?php
/**
* 移除手机号首位0并添加国家代码前缀
* @param string $phone 原始手机号
* @param string $countryCode 国家代码 默认86
* @return string 格式化后的手机号
*/
function formatPhoneWithCountryCode($phone, $countryCode = '86') {
// 去除手机号中的空格等非数字字符
$cleanPhone = preg_replace('/D/', '', $phone);
// 判断首位是否为0
if (strpos($cleanPhone, '0') === 0) {
// 截取从第二位开始的所有字符
$cleanPhone = substr($cleanPhone, 1);
}
// 拼接国家代码返回
return $countryCode . $cleanPhone;
}
// 测试示例
$testPhone = '013800138000';
$result = formatPhoneWithCountryCode($testPhone);
echo $result; // 输出 8613800138000
?>
代码说明
首先使用preg_replace函数去掉手机号中可能存在的空格、横线等非数字字符,避免输入格式问题导致处理错误。然后通过strpos判断手机号首位是否为0,如果是则使用substr截取从索引1开始的所有字符,最后拼接上指定的国家代码返回。
Laravel框架下的实现
在Laravel项目中,我们可以将手机号格式化的逻辑封装成服务类,方便在控制器、队列等多个地方复用,同时可以结合Laravel的验证规则确保输入合法性。
创建手机号格式化服务
首先创建服务类,存放到app/Services/PhoneService.php:
<?php
namespace AppServices;
class PhoneService
{
/**
* 格式化手机号为带国家代码的格式
* @param string $phone 原始手机号
* @param string $countryCode 国家代码 默认86
* @return string
*/
public function formatWithCountryCode(string $phone, string $countryCode = '86'): string
{
// 清理非数字字符
$cleanPhone = preg_replace('/D/', '', $phone);
// 处理首位0的情况
if (str_starts_with($cleanPhone, '0')) {
$cleanPhone = substr($cleanPhone, 1);
}
return $countryCode . $cleanPhone;
}
}
?>
在控制器中使用服务
在控制器中注入服务类,处理用户提交的手机号:
<?php
namespace AppHttpControllers;
use AppServicesPhoneService;
use IlluminateHttpRequest;
class UserController extends Controller
{
protected PhoneService $phoneService;
public function __construct(PhoneService $phoneService)
{
$this->phoneService = $phoneService;
}
public function store(Request $request)
{
$request->validate([
'phone' => 'required|string|size:11',
]);
$rawPhone = $request->input('phone');
$formattedPhone = $this->phoneService->formatWithCountryCode($rawPhone);
// 后续存储或业务逻辑处理
return response()->json(['formatted_phone' => $formattedPhone]);
}
}
?>
自定义验证规则(可选)
如果需要验证格式化后的手机号,可以创建自定义验证规则,存放到app/Rules/ValidInternationalPhone.php:
<?php
namespace AppRules;
use IlluminateContractsValidationRule;
use AppServicesPhoneService;
class ValidInternationalPhone implements Rule
{
protected PhoneService $phoneService;
public function __construct(PhoneService $phoneService)
{
$this->phoneService = $phoneService;
}
public function passes($attribute, $value)
{
$formatted = $this->phoneService->formatWithCountryCode($value);
// 简单验证 国家代码+手机号总长度 比如86+10位手机号 共12位
return strlen($formatted) === 12;
}
public function message()
{
return '手机号格式不正确,无法转换为合法的国际格式';
}
}
?>
注意事项
- 处理前建议先清理手机号中的非数字字符,避免用户输入的空格、横线等影响处理逻辑。
- 如果业务涉及多个国家,可以维护一个国家代码与手机号规则的映射表,根据用户输入的地区自动匹配对应的国家代码。
- 存储手机号时建议统一存储格式化后的国际格式,避免后续业务处理时重复转换。
- 如果手机号首位不是0,不需要做截取操作,直接拼接国家代码即可,避免误处理非国内格式的手机号。