如何解析没有特殊字符的手机号码

How to parse mobile number without special character

我想解析一个没有特殊字符的手机号码

+61-426 861 479 ====>  61 426 861 479

PHP preg_match_all

preg_match_all('/(\d{2}) (\d{3}) (\d{3}) (\d{3})/', $part,$matches);
if (count($matches[0])){
    foreach ($matches[0] as $mob) {
        $records['mobile'][] = $mob;
    }
}

预期输出

+61-426 861 479 ====>  61 426 861 479

您的模式中缺少 +-。您可以更新您的模式以使用 2 个捕获组并使用 preg_match_all。要将手机号码添加到数组中,您可以连接第一个和第二个索引。

\+(\d{2})-(\d{3}(?: \d{3}){2})\b

Regex demo | Php demo

例如

$part = "+61-426 861 478 +61-426 861 479 ";
preg_match_all('/\+(\d{2})-(\d{3}(?: \d{3}){2})\b/', $part, $matches, PREG_SET_ORDER, 0);

if (count($matches)) {
    foreach ($matches as $mob) {
        $records['mobile'][] = $mob[1] . ' ' . $mob[2];
    }
}

print_r($records);

结果

Array
(
    [mobile] => Array
        (
            [0] => 61 426 861 478
            [1] => 61 426 861 479
        )

)

如果数字是唯一的字符串,您也可以使用 \D+ 删除所有非数字并替换为 space。然后使用 ltrim 从 + 中删除前导 space。看到一个php demo.