2013-02-26 76 views
0

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

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; 
    } 
+0

你怎么知道“07856555333”是英国或印度号码? – stema 2013-02-26 11:57:40

+0

我们可以根据语言环境进行识别,即用户在我们的.co.uk网站或我们的.co.in网站 – user1746582 2013-02-26 12:01:12

回答

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 
     } 
    } 
+0

上提交的电话号码非常感谢。我会尽快尝试,并让你知道它是如何:) – user1746582 2013-02-26 14:33:24

+0

刚刚尝试过,它完美的作品。如果没有返回,那么它是无效的。我会+2,如果我可以:-) – user1746582 2013-02-26 18:08:18