-2

可能重复:
黎巴嫩电话号码
preg_replace 的 PHP 正则表达式以掩盖电话号码的一部分

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

例如 :

+622112345、622112345 和 02112345

现在,问题是......我只想以一种格式存储电话号码,即: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 之外,还有其他方法可以做到这一点吗?例如,使用正则表达式...

4

2 回答 2

2

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

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中看到,这为所有测试用例正确创建了正确的字符串。

于 2012-08-08T15:08:11.583 回答
0
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
}

那只是更短

于 2012-08-08T15:18:54.483 回答