【问题标题】:Validate Phone Prefix With Country Code : IF vs RegEx [duplicate]使用国家/地区代码验证电话前缀:IF vs RegEx [重复]
【发布时间】:2012-08-08 23:31:36
【问题描述】:

可能重复:
PHP regex for Lebanese phone number
preg_replace to mask parts of a phone number

在我的国家,电话号码前缀有 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 之外,还有其他方法可以做到这一点吗?例如,使用 RegEx...

【问题讨论】:

  • 这个问题已经得到解答,尽管在其他国家,herehere

标签: php


【解决方案1】:

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

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

您可以从the demo 看到,这为所有测试用例正确地创建了正确的$output 字符串。

【讨论】:

  • 兄弟,你的代码给了我这个:输入:+622112345,输出:02112345(正确);输入:622112345,输出:02112345(再次更正);输入:081212345,输出:01212345(缺少8,应该是081212345)
  • CAPS 怎么了?问题是(\d{7}),它假设电话号码是 7 位数字。如果可以是7或者8,改成(\d{7,8})
  • 我将我的答案更新为包含 7 位或 8 位电话号码,您可以看到 here 已通过所有测试用例。
【解决方案2】:
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
}

那就更短了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 2017-03-30
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多