【问题标题】:formatting local phone numbers into international (knowing countries)将本地电话号码格式化为国际(了解国家)
【发布时间】:2016-07-27 00:50:09
【问题描述】:

我使用 SMS API 向手机发送确认码。
它的参数要求我将访客电话号码格式设置为国际,例如 +9912345678 而不是 012 345 678。
考虑到我知道用户的国家(来自选择输入)和号码(来自文本输入),我知道他在上一个网页?

【问题讨论】:

    标签: php regex internationalization phone-number


    【解决方案1】:

    您只需将 0 替换为国家/地区代码即可非常轻松地做到这一点。

    例子:

    $originalNumber = '012345678';
    $countryCode = '+99'; // Replace with known country code of user.
    $internationalNumber = preg_replace('/^0/', $countryCode, $originalNumber);
    echo $internationalNumber; // Will output: +9912345678
    

    希望这会有所帮助。

    【讨论】:

    • 但是在这里,您不会按照问题的要求删除空格!
    【解决方案2】:

    我之前使用过这个库(没有作曲家)并且运行良好:https://github.com/davideme/libphonenumber-for-PHP

    您只需要在您的 php 中 include PhoneNumberUtil.php 并且该文件知道还需要包含什么。

    你可以像这样格式化一个数字:

    $swissNumberStr = "044 668 18 00";
    $phoneUtil = PhoneNumberUtil::getInstance();
    try {
        $swissNumberProto = $phoneUtil->parseAndKeepRawInput($swissNumberStr, "CH");
        var_dump($swissNumberProto);
    } catch (NumberParseException $e) {
        echo $e;
    }
    echo $phoneUtil->format($swissNumberProto, PhoneNumberFormat::INTERNATIONAL)
    

    查看demo.php 以查看有关如何使用库的更多示例。

    【讨论】:

      【解决方案3】:

      根据@Huso 的回答,我编写了以下函数来格式化和清理(删除破折号、圆点和空格)电话号码:

      function phonize($phoneNumber, $country) {
      
          $countryCodes = array(
              'ch' => '+41',
              'de' => '+43',
              'it' => '+39'
          );
      
          return preg_replace('/[^0-9+]/', '',
                 preg_replace('/^0/', $countryCodes[$country], $phoneNumber));
      }
      

      使用:

      $phone   = '022 123 43 65';
      $country = 'ch';
      
      $phone   = phonize($phone, $country);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-19
        • 1970-01-01
        • 2013-11-02
        • 1970-01-01
        • 2022-12-21
        相关资源
        最近更新 更多