Files
fdesk/app/inquiry/utils/PhoneCountryHelper.php
T

59 lines
1.4 KiB
PHP
Raw Normal View History

2025-12-10 20:18:46 +08:00
<?php
namespace app\inquiry\utils;
use support\Db;
class PhoneCountryHelper
{
/**
* 根据电话/WhatsApp 号码识别国家 ID
* 号码格式可以是:+996557660304、996557660304、00996557660304 等
*/
public static function detectCountryId(?string $rawPhone): ?int
{
if (!$rawPhone) {
return null;
}
// 1. 只保留数字和+
$phone = preg_replace('/[^\d\+]/', '', $rawPhone);
if ($phone === '' || $phone === null) {
return null;
}
// 2. 统一前缀:00 开头 -> +
if (str_starts_with($phone, '00')) {
$phone = '+' . substr($phone, 2);
} elseif ($phone[0] !== '+') {
// 没有 +,默认补一个(大多数线索都是国际号)
$phone = '+' . $phone;
}
$digits = ltrim($phone, '+');
if ($digits === '') {
return null;
}
// 3. 国家区号最长 3 位,从长到短匹配
for ($len = 3; $len >= 1; $len--) {
$code = substr($digits, 0, $len);
if ($code === '') {
continue;
}
$country = Db::table('country')
->where('phone_code', $code)
->first();
if ($country) {
return (int)$country->id;
}
}
// 没找到
return null;
}
}