南非手机号码格式

时间:2011-01-16 14:51:56

标签: php regex mobile

我仍然试图了解PHP中的preg_replace函数。如何将以下手机号码格式化为标准27xxxxxxxxx以获取手机号码?

例如:

083-123-4678应为27831234567 +278312345678应该是27831234567

起始数字全部必须为081,082,083,084或071,072,073,074

2 个答案:

答案 0 :(得分:2)

    function Number_SA($numbers)
{
$number = preg_replace(array('~[^0-9]~', '~^27~'), '', $numbers);

    if (preg_match('~^(?:07[1234])~', $number) > 0)
    {
        $output= sprintf('%d%s', 27, $number);if ((strlen($output) < 12)| (strlen($output) > 13)){ return false;}
         else{return $output;}

    }
    elseif (preg_match('~^(?:08[123458])~', $number) > 0)
    {
        $output= sprintf('%d%s', 27, $number);if ((strlen($output) < 12)| (strlen($output) > 13)){ return false;}
         else{return $output;}

    }
    elseif (preg_match('~^(?:01[123468])~', $number) > 0)
    {
        $output= sprintf('%d%s', 27, $number);
        if ((strlen($output) < 12)| (strlen($output) > 13)){ return false;}
         else{return $output;}

    }
    elseif (preg_match('~^(?:02[1])~', $number) > 0)
    {
        $output= sprintf('%d%s', 27, $number);

         if ((strlen($output) < 12)| (strlen($output) > 13)){ return false;}
         else{return $output;}

    }       
    elseif (preg_match('~^(?:03[1])~', $number) > 0)
    {
        $output= sprintf('%d%s', 27, $number);
        if ((strlen($output) < 12)| (strlen($output) > 13)){ return false;}
         else{return $output;}

    }  
    elseif (preg_match('~^(?:04[0134])~', $number) > 0)
    {
        $output= sprintf('%d%s', 27, $number);
        if ((strlen($output) < 12)| (strlen($output) > 13)){ return false;}
         else{return $output;}

    }  
    elseif (preg_match('~^(?:05[17])~', $number) > 0)
    {
        $output= sprintf('%d%s', 27, $number);
        if ((strlen($output) < 12)| (strlen($output) > 13)){ return false;}
        else{return $output;}

    }  
    else{return false;}

return false;
}


$phoneno=array();
array_push($phoneno,(Number_SA('083-313-2605'))); //true
array_push($phoneno,(Number_SA('067-313-26055')));//false
array_push($phoneno,(Number_SA('021-313-260'))); //false
array_push($phoneno,(Number_SA('0211-313-8903')));//true



foreach ($phoneno as $number){
if($number == ""){ echo "Phone Number is null"."<br/>";}
else{ echo "This is valid: ".$number."<br/>";}}

答案 1 :(得分:1)

这应该这样做:

function Number_SA($number)
{
    $number = preg_replace(array('~[^0-9]~', '~^27~'), '', $number);

    if (preg_match('~^(?:07[1234]|08[1234])~', $number) > 0)
    {
        return sprintf('%d%s', 27, $number);
    }

    return false;
}

用法:

var_dump(Number_SA('083-123-4678'));    // 27831234567
var_dump(Number_SA('085-123-4678'));    // false
var_dump(Number_SA('+278312345678'));   // false (doesn't start with 083)