这是我的工作代码,如果你在下面有一个更好的帖子。
花了我几个小时来建造。 数字可以在(4-15)通用标准之间。 可能包含' +'在开始时' - '允许格式为(' 1 + 123,12 + 123,+ 1-123,+ 12-123)。 休息所有空间和' - '和' +'将被空白替换,并返回正确的数字。
public function validateMobileNumber($mobile){
$mobile = str_replace(' ','',$mobile);//remove all the blank spaces i.e +1-123456342234
//now let's do it for mobile numbers
if(preg_match('/^([0-9,\\-,+,]){4,15}$/', $mobile)){//pratially valid number
$mobile = rtrim($mobile, "+");
$mobile = trim($mobile, "-");
//removing multiple '-'
$mobile_arr = explode('-',$mobile);//elplode a number like +1-123 456-342-234
$sub1 = $mobile_arr[0];//+1
if(strlen($sub1) != strlen($mobile)){ // condition where 12345678 valid nos is detected
$check_plus = explode('+',$sub1); //logic to detect number starts with +1-123.. or +12-123.. or 1-123.. or 12-123...
if($check_plus[0] == ''){ // occurs when we get +1...
if(strlen($sub1) == 2 || strlen($sub1) == 3){//valid digits like +1-123, +12-123
unset($mobile_arr[0]);
} else {
//invlid number
return array('status'=>'error','message'=>'Number must be in +1-123.. or +12-123.. or 1-123.. or 12-123... format');
}
} else {
if(strlen($sub1) == 1 || strlen($sub1) == 2){//valid digits like 1-123, 12-123
unset($mobile_arr[0]);
} else {
//invlid number
return array('status'=>'error','message'=>'Number must be in 1-123.. or 12-123.. or +1-123.. or +12-123... format');
}
}
$mobile = $sub1 .'-'.implode('',$mobile_arr);//+1-123 456342234
}
//removing '-' ends
//removing '+'
$mobile_arr = explode('+',$mobile);//explode a number like +1-123 456+342-234
if($mobile_arr[0]!='') {
if (strlen($mobile_arr[0]) != strlen($mobile)){ //number might be 1-123 456+342-234+
return array('status'=>'error','message'=>'Number must have "+" at the start ');
}
} else {
if($mobile_arr[2]!=''){//when we have more than one +
$sub1 = $mobile_arr[1];
unset($mobile_arr[1]);
$mobile = '+'.$sub1.implode('',$mobile_arr);//+1-123 456342234
}
}
return array('status'=>'success','data'=>$mobile);
} else {
return array('status'=>'error','message'=>'Invalid Mobile Number.');
}
//Validate Mobile number logic ends
}