0

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

1 に答える 1

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
       }
  }
于 2013-02-26T12:38:12.103 に答える