在PHP中将本地移动设备格式化为国际

时间:2013-02-26 11:54:41

标签: php regex mobile formatting sms

我正在寻找一个简单的正则表达式,使用PHP将英国(44)和印度(91)数字转换为有效的国际格式。所需格式为:

447856555333 (for uk mobile numbers)
919876543456 (for indian mobile numbers)

我需要一个接受并格式化以下变体的正则表达式:

1) 07856555333
2) 0785 6555333
3) 0785 655 5333
4) 0785-655-5333
5) 00447856555333
6) 0044785 6555333
7) 0044785 655 5333
8) 0044785-655-5333
9) 00447856555333
10) +447856555333
11) +44785 6555333
12) +44785 655 5333
13) +44785-655-5333
14) +919876543456
15) 00919876543456

非常感谢任何帮助。

更新:基于以下答案,我稍微修改了代码并且效果很好。它不是防弹,但涵盖了大多数流行的格式:

    public static function formatMobile($mobile) {
        $locale = '44'; //need to update this
        $sms_country_codes = Config::get('sms_country_codes');

        //lose any non numeric characters
        $numeric_p_number = preg_replace("#[^0-9]+#", "", $mobile);
        //remove leading zeros
        $numeric_p_number = preg_replace("#^[0]*#", "", $numeric_p_number);
        //get first 2 digits
        $f2digit = substr($numeric_p_number, 0,2);

        if(strlen($numeric_p_number) == 12) {
            if(in_array($f2digit, $sms_country_codes) ) {
                //no looks ok 
            }
            else {
                return ""; //is correct length but missing country code so must be invalid!
            }
        }
        else {
            if(strlen($locale . $numeric_p_number) == 12 && !(in_array($f2digit, $sms_country_codes))) {
                $numeric_p_number = $locale . $numeric_p_number;
                //the number is ok after adding the country prefix
            } else {
                //something is missing from here
                return "";
            }
        }

        return $numeric_p_number;
    }

2 个答案:

答案 0 :(得分:1)

对于你的特定范围,认为这样的事情可能有用...不是真正的正则表达式解决方案,但应该为你的需求做到这一点:

  $locale = "your_locale_prefix";
  $valid_codes = array("44","91");
  //loose any non numeric characters
  $numeric_p_number = preg_replace("#[^0-9]+#", "", $phone_number);
  //remove leading zeros
  $numeric_p_number = preg_replace("#^[0]*#", "", $numeric_p_number);
  //get first 2 digits
  $f2digit = substr($numeric_p_number, 0,2);
  if(in_array($f2digit, $valid_codes) && strlen($numeric_p_number) == 12){
         //code is ok 
  } else {
       if(strlen($locale . $numeric_p_number) == 12) {
           //the number is ok after adding the country prefix
       } else {
           //something is missing from here
       }
  }

答案 1 :(得分:0)