我试图将电话号码转换为我们用PHP输入电话号码
使用其他方法可以正常工作,但我想使用regExp RegExp的初学者,与我尝试过的一些代码相混淆 提供php代码以更好地理解
示例 1(800)205 – 1111-> + 1-800-205-1111
+341932831111-> + 34-193-283-1111
01932831111-> + 0-193-283-1111
+12 21 2501 1111-> + 12-212-501-1111
21111-> + 2-1111
// Strip all non-numeric characters
$phone = preg_replace("/[^0-9]/", "", $phone);
//Calculating the length of the phone number
$phoneNumberLength = strlen($phone);
// Using switch condition by phone number length
switch( $phoneNumberLength ) {
case $phoneNumberLength <= 7:
$phone = prepare_phone_number(substr($phone, 0, 1), substr($phone, 1, 4), NULL, NULL);
break;
case 10:
// If we have 10 digits and 1 not the first, add 1
$phone = '1' . $phone;
$phone = prepare_phone_number(substr($phone, 0, 1), substr($phone, 1, 3), substr($phone, 4, 3), substr($phone, 7, 4));
break;
case 11:
$phone = prepare_phone_number(substr($phone, 0, 1), substr($phone, 1, 3), substr($phone, 4, 3), substr($phone, 7, 4));
break;
default:
$phone = prepare_phone_number(substr($phone, 0, 2 ), substr($phone, 2, 3 ), substr($phone, 5,3), substr($phone, 8,4));
}
return $phone;
}
// Created new function to concat phone number in proper US format
function prepare_phone_number($param1, $param2, $param3, $param4)
{
return implode( '-', array_filter( [ '+' . $param1, $param2, $param3, $param4 ] ) );
}
答案 0 :(得分:1)
我对您的问题有一个答案,也请确保有很多使用正则表达式执行任何操作的方法,所以我并不是说我的答案是最好的,但是我认为它可以满足您的要求:-< / p>
字符串反转功能
strrev(str)
正则表达式模式
/(1{4})(\d{3})?(\d{3})?(\d{1,3})/
执行我所描述的代码:-
$phone = '01932831111'
/*reverse phone number*/
$phone = strrev($phone);
/*replace with (-) and (+) which do you want*/
$reg_result = preg_replace('/(1{4})(\\d{3})?(\\d{3})?(\\d{1,3})/', '$1-$2-$3-$4+', $phone);
/*if there was two captured boxes*/
$res_2 = str_replace('--', '-', $reg_result);
/*if there was three captured boxes*/
$res_1 = str_replace('---', '-', $reg_result);
/*finally reverse the string to get the result*/
$result = strrev($res_1);
echo $result;
结果
+0-193-283-1111