正则表达式格式化手机号码

时间:2018-05-15 19:14:35

标签: php regex php-7

我有以下PHP格式化MobileNumber

<?php

function formatMobileNumberWithDialingCode($mobileNo, $defaultDialingCode = '')
{
    $validDialingCodes = [
        357,
        385,
        371
    ];

    if (preg_match('/^(\+|00)/', $mobileNo)) {
        $tempMobileNo = preg_replace('/^(\+|00)(.*?)/', "$2", $mobileNo);
        foreach ($validDialingCodes as $dialingCode) {
            if (preg_match('/^' . $dialingCode . '/', $tempMobileNo, $matches)) {
                $tempMobileNo = preg_replace('/^(' . $dialingCode . '(0+)?)(.*?)/', $dialingCode . "$2", $tempMobileNo);
                break;
            }
        }
        return $tempMobileNo;
    }

    // Add 0 or 00 if it starts from 0{dialing} or {dialing}
    $convertedMobileNo = '00' . $defaultDialingCode . $mobileNo;
    foreach ($validDialingCodes as $dialingCode) {
        if (preg_match('/^' . $dialingCode . '/', $mobileNo)) {
            $convertedMobileNo = preg_replace('/^(' . $dialingCode . ')(0+)?(.*?)/', '00' . $dialingCode . "$3", $mobileNo);
            break;
        }
    }
    return preg_replace('/^(\+|00)(.*?)/', "$2", $convertedMobileNo);
}

$mobileNoSamples = [
    '385' => [
        '441234568',
        '+371441234568',
        '+3850441234568',
        '00385441234568'
    ],
    '371' => [
        '551234567',
        '+385551234567',
        '+3710551234567',
        '00371551234567'
    ]
];    foreach ($mobileNoSamples as $dialingCode => $mobileNos) {
        foreach ($mobileNos as $mobileNo) {
            echo '(' . $dialingCode . ') ' . $mobileNo . ' -> ' . formatMobileNumberWithDialingCode($mobileNo, $dialingCode) . PHP_EOL;
        }
    }

哪个输出为

(385) 441234568 -> 385441234568 [CORRECT]
(385) +371441234568 -> 371441234568 [CORRECT]
(385) +385441234568 -> 385441234568 [CORRECT]
(385) +3850441234568 -> 3850441234568 [WRONG] (CORRECT - 385441234568)
(385) 00385441234568 -> 385441234568 [CORRECT]
(371) 551234567 -> 371551234567 [CORRECT]
(371) +385551234567 -> 385551234567 [CORRECT]
(371) +371551234567 -> 371551234567 [CORRECT]
(371) +3710551234567 -> 3710551234567 [WRONG] (CORRECT - 371551234567)
(371) 00371551234567 -> 371551234567 [CORRECT]

正如您所看到的那样,拨号代码(应该删除)后立即为0的数字格式不正确。
任何人都可以帮我修改函数来修复[WRONG]个案例吗?

正确格式 - [InternationalDialingCode Without leading + or 00] [Mobile Number without leading Zero]

由于

1 个答案:

答案 0 :(得分:0)

您可以将+00之后的第一个数字限制为“0”之外的任何数字。

/^(\+|00)?([1-9]\d+)$/