【问题标题】:How to match the prefix of a number in php using preg_match如何使用preg_match在php中匹配数字的前缀
【发布时间】:2015-12-13 22:58:16
【问题描述】:

我正在尝试检查数字的前缀。以下是我的代码;

   if (preg_match('[^\070|071|072|25470|25471|25472]', $phoneno)) {
                $countryCode="254";
                $newNumber = preg_replace('/^0?/', $countryCode, $phoneno);
                  } else {
                $response = array("status_code"=>"1234","message"=>"Invalid Phone number");
                $this->response(json_encode($response),200,$this->callback);
        }

每次发出请求时,我得到的响应都是“电话号码无效”。

【问题讨论】:

  • | 在字符类中不再是 OR。在一个字符类中,字符没有顺序,写[070|074][|047]一样,只匹配一个字符。
  • /^0?/ 匹配世界上所有的字符串,因为第一个唯一的字符是可选的。
  • 我猜你的意思是preg_match('/^(070|071|072|25470|25471|25472)/', $phoneno),是吗?这将在字符串的开头找到交替出现的数字。什么是有效输入和无效输入?
  • 更短! preg_match('/^(254|0)(70|71|72)/', $phoneno);
  • @stribizhev 仍然会产生同样的错误

标签: php regex preg-replace preg-match preg-match-all


【解决方案1】:

这对我有用:

$phonenos = [
    "25470666666",
    "25471666666",
    "25472666666",
    "070666666",
    "071666666",
    "072666666",
    "justtesting",
    "666666",
];

foreach($phonenos as $phoneno) {
    if (preg_match('/^(254|0)(70|71|72)/', $phoneno)) {
        $countryCode = "254";
        $newNumber = preg_replace('/^0/', $countryCode, $phoneno);
        print("matched<br>\n");
    } else {
        print("not matched<br>\n");
    }
}

【讨论】:

    猜你喜欢
    • 2015-06-27
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 2015-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多