如何解析不带特殊字符的手机号码

时间:2019-06-26 07:18:56

标签: php preg-match-all

我想解析一个不带特殊字符的手机号码

<example Hostname="https://xxx.build" ClientSecretKey="myclientsecret">/example>

PHP preg_match_all

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

预期产量

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;
    }
}

1 个答案:

答案 0 :(得分:0)

您丢失了模式中的#create dictionary city_dict = {'Kenora':'X','Niagara':'X'} mapping_expr = create_map([lit(x) for x in chain(*city_dict .items())]) #lookup and replace df= df.withColumn('new_city', mapping_expr[df['city']]) #But it gives me wrong results. df.groupBy('new_city').count().show() new_city count X 2 null 3 +。您可以更新模式以使用2个捕获组并使用preg_match_all。要将移动电话号码添加到数组中,可以串联第一个索引和第二个索引。

-

Regex demo | Php demo

例如

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

结果

$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 ) ) 删除所有非数字并用空格替换。然后使用ltrim从\D+中删除前导空格。参见php demo