简体   繁体   中英

strip international calling code from phone number using php

I have php mysql application and i want the phone numbers be saved in a specific format. after some googling i reached up to this function:

function RemoveExt($phone) {
    if(substr($phone,0,1) == '+' || substr($phone, 0,2) == 00){
        $phone = preg_replace('/[^\d]/', '', $phone);
        }

    $phone=trim($phone);
    $prefixs=array('0097150','0097156','0097152','0097155', '97150','97156','97155','97152','050','056','055','052','00');

    $replace=array('050','056','052','055','050','056','055','052','050','056','055','052','00');
      $count = count($prefixs); 
for($i = 0; $i < $count; $i++)
    {
        if(strncmp($phone, $prefixs[$i], strlen($prefixs[$i])) == 0){

            $phone = preg_replace('/^'.$prefixs[$i].'/i','',$phone);
             $ext=$replace[$i];
            return array('phone' => $phone, 'ext' => $ext);
        }else{
        return array('phone' => $phone, 'ext' => $ext); 
        } 
    }
}

for example the phone number +971501234567 => "+" will be the international code, "971" will be the country code, "50" will be the mobile network code and "1234567" will be the mobile number.

noted that we have more than one mobile code. The question that I need to save two parts from the number (mobile network code, mobile number) for example: +971501234567 will be saved as (050) the mobile network code and (1234567) the mobile number.

could anyone help me to achive that?.

If they always take the form of +971501234567 just chop off the last 9 numbers. From these, take the last seven as the mobile number, prepend the first two with a 0 as the mobile network.

I am going to share the working class :-

    function RemoveExt($phone) {

    if(substr($phone,0,1) == '+'){
        $phone = preg_replace('/[^\d]/', '00', $phone);
        }

    $prefix=array('0097150','0097156','0097155','0097152','97150','97156','97155','97152','050','056','055','052','00');

    $replace=array('050','056','055','052','050','056','055','052','050','056','055','052','00');
      $count =count($prefix);
      $counter=0;
      while( $counter < $count){
            if(strncmp($phone, $prefix[$counter] , strlen($prefix[$counter])) == 0){

                $phone=substr($phone, strlen($prefix[$counter]));
                $ext=$replace[$counter];

            }
            $counter++;
        }
        return array('phone' => $phone, 'ext' => $ext);
}

Hope help someone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM