使用国家/地区代码验证电话前缀:IF 与正则表达式


Validate Phone Prefix With Country Code : IF vs RegEx

可能的重复项:
黎巴嫩电话号码
的PHP正则表达式 preg_replace屏蔽电话号码的某些部分

在我的国家,电话号码前缀有 3 种输入可能性:+62、62 和 0。

例如:

+622112345, 622112345和02112345

现在,问题是...我想以 1 种格式存储电话号码,即:0xxxx。意味着,任何电话前缀都将转换为 0xxxx 格式。

输入 : +622112345, 输出 : 02112345

输入 : 622112345, 输出 : 02112345

输入 : 02112345

, 输出 : 02112345

我认为通过使用substr()函数和IF可以解决这种情况:

$Prefix = substr($Number, 0, 2);
if ($Prefix = "+6"){
//some code to convert +62 into 0
}else if ($Prefix = "62"){
//some code to convert 62 into 0
}else{
//nothing to do, because it's already 0
}

除了使用IF之外,还有其他方法可以做到这一点吗? 例如,使用正则表达式...

是的,这在单个正则表达式中要容易得多:

preg_match( '/(0|'+?'d{2})('d{7,8})/', $input, $matches);
echo $matches[1] . ' is the extension.' . "'n";
echo $matches[2] . ' is the phone number.' . "'n";

这将从任一输入中捕获分机和电话号码。但是,对于您的特定情况,我们可以创建一个测试台并使用preg_replace()来获取所需的输出字符串:

$tests = array( '+622112345' => '02112345', '622112345' => '02112345', '02112345' => '02112345');
foreach( $tests as $test => $desired_output) {
    $output = preg_replace( '/(0|'+?'d{2})('d{7,8})/', '0$2', $test);
    echo "Does $output match $desired_output? " . ((strcmp( $output, $desired_output) === 0) ? "Yes" : "No") . "'n";
}

您可以从演示中看到,这是为所有测试用例正确创建正确的$output字符串。

if (preg_match('[^'+62|62]', $your_phone_number)) {
    # if string contains +62 or 62 do something with this number
} else {
    # do nothing because string doesn't contain +62 or 62
}

那只是更短