我正在尝试验证用户注册/编辑表单上的电话号码。有两个字段:电话号码1和电话号码2。它们可能会填写,也可能不填写。如果它们被填充,我将不得不提取它的数字,并使用正则表达式,正确地格式化它并显示它,以便用户可以编辑。问题是我是一个初学者,我不能格式化它。下面是代码:
if (!empty($phone_1 )) {
$string = $phone_1;
$newString = preg_replace('/[^0-9]/i', '', $string); //extract numbers
$regex = '^(11 [9][0-9]{4}-[0-9]{4})|(\(1[2-9]\) [5-9][0-9]{3}-[0-9]{4})|(\ ([2-9][1-9]\) [5-9][0-9]{3}-[0-9]{4})$';
$final = preg_replace($regex, '', $newString);
}我尝试输出的格式是"99 99999.9999“。
谢谢。
发布于 2014-09-03 23:07:21
为什么不使用sub_str来格式化字符串呢?
$phone1="01234567890";
$phone1 = substr($phone1, 0, 2) . ' ' . substr($phone1, 2, 5) . '.' . substr($phone1, 7, 4);
echo $phone1;输出:
01 23456.7890发布于 2014-09-03 23:14:01
如果您想使用正则表达式,您可以使用以下命令:
^(\d\d)(\d{5})(\d{4})$

您可以使用的代码是:
$re = "/^(\\d\\d)(\\d{5})(\\d{4})$/";
$str = "01234567890";
$subst = '\1 \2.\3';
$result = preg_replace($re, $subst, $str, 1);https://stackoverflow.com/questions/25647701
复制相似问题