PHP交换0与+;44
我得到以下变量PHP交换0与+;44,php,regex,preg-replace,phone-number,Php,Regex,Preg Replace,Phone Number,我得到以下变量 $inputMobile = $_POST["inputMobile"]; 现在数字可以以多种方式出现,例如 07714.... +447714... 00447714... 我需要做的是确保无论我得到什么数字,我都将其更改为+44开头。我吃过类似的东西 $inputMobile = $_POST["inputMobile"]; if (substr($inputMobile, 0, 1) === '+44') { $inputMobile = $_
$inputMobile = $_POST["inputMobile"];
现在数字可以以多种方式出现,例如
07714....
+447714...
00447714...
我需要做的是确保无论我得到什么数字,我都将其更改为+44开头。我吃过类似的东西
$inputMobile = $_POST["inputMobile"];
if (substr($inputMobile, 0, 1) === '+44') {
$inputMobile = $_POST["inputMobile"];
}
else {
$inputMobile = preg_replace('/^0?/', '+44', $inputMobile);
}
问题是,如果我给它一个像+447714这样的数字,它返回+44+44714
我怎样才能阻止这种事情发生
谢谢正如其他人指出的那样,通过将3个字符的字符串(
+44
)与1个字符的字符串(substr(inputMobile,0,1)
)进行比较,您正在错误地使用substr
)。请尝试以下方法:
$inputMobile = $_POST["inputMobile"];
$inputMobile = preg_replace('/^(0*44|(?!\+0*44)0*)/', '+44', $inputMobile);
这是用+44
替换前导的044
或44
(以及后面的任何零),如果数字没有前导的044
或44
,只需在开头添加+44
。以下例子:
07714....
+447714...
00447714...
都标准化并成为+447714
正如其他人所指出的,通过将3个字符的字符串(+44
)与1个字符的字符串(substr(inputMobile,0,1)
)进行比较,您正在错误地使用substr
)。请尝试以下方法:
$inputMobile = $_POST["inputMobile"];
$inputMobile = preg_replace('/^(0*44|(?!\+0*44)0*)/', '+44', $inputMobile);
这是用+44
替换前导的044
或44
(以及后面的任何零),如果数字没有前导的044
或44
,只需在开头添加+44
。以下例子:
07714....
+447714...
00447714...
都是标准化的,成为+447714
“如果第一个字符是这三个字符的序列…”可能是问题的症结所在。substr($inputMobile,0,1)=='+44'
永远不可能是真的“如果第一个字符是这三个字符的序列…”这可能是问题的症结所在。substr($inputMobile,0,1)=='+44'
永远不可能是true
。