[英]Standardize/Sanitize variably-formatted phone numbers to be purely 10-digit strings
在我将用户提供的电话号码存储在我的数据库中之前,我需要对字符串进行标准化/清理,使其恰好包含 10 位数字。
我想从所有这些潜在的输入值中得到1112223333
:
(111)222-3333
111-222-3333
111.222.3333
+11112223333
11112223333
在最后两个字符串中,有一个 1 作为国家代码。
我能够在以下方面取得一些进展:
preg_replace('/\D/', '', mysqli_real_escape_string($conn, $_POST["phone"]));
谁能帮我修复超过 10 位数字的字符串?
使用你的 preg_replace ,除了最后一个。 接下来计算字符串的长度,如果超过 9 个数字,则删除第一个数字。
preg_replace('/\D/', '', mysqli_real_escape_string($conn, $_POST["phone"]));
if(strlen($str) > 9){
$str = substr($str, 1);
}
如果你想解析电话号码,一个非常有用的库是giggsey/libphonenumber-for-php 。 它基于谷歌的 libphonenumber,它还有一个在线演示来展示它是如何工作的
分两次执行:
$phone = [
'(111)222-3333',
'111-222-3333',
'111.222.3333',
'+11112223333',
'11112223333',
'+331234567890',
];
# remove non digit
$res = preg_replace('/\D+/', '', $phone);
# keep only 10 digit
$res = preg_replace('/^\d+(\d{10})$/', '$1', $res);
print_r($res);
输出:
Array
(
[0] => 1112223333
[1] => 1112223333
[2] => 1112223333
[3] => 1112223333
[4] => 1112223333
[5] => 1234567890
)
此任务可以/应该通过只遍历字符串来替换不需要的字符来完成。
.* #greedily match zero or more of any character
(\d{3}) #capture group 1
\D* #greedily match zero or more non-digits
(\d{3}) #capture group 2
\D* #greedily match zero or more non-digits
(\d{4}) #capture group 3
$ #match end of string
匹配字符串结尾的位置可确保捕获字符串的最后 10 位数字,并忽略字符串前面的任何额外数字。
代码:(演示)
$strings = [
'(111)222-3333',
'111-222-3333',
'111.222.3333',
'+11112223333',
'11112223333'
];
foreach ($strings as $string) {
echo preg_replace(
'/.*(\d{3})\D*(\d{3})\D*(\d{4})$/',
'$1$2$3',
$string
) . "\n---\n";
}
输出:
1112223333
---
1112223333
---
1112223333
---
1112223333
---
1112223333
---
通过将第三个捕获组更改为前瞻并且仅在替换字符串中使用两个反向引用,可以实现相同的结果。 (演示)
echo preg_replace(
'/.*(\d{3})\D*(\d{3})\D*(?=\d{4}$)/',
'$1$2',
$string
);
最后,可以使用更简单的模式来清除所有非数字,但仅此一项不会将字符串修剪到 10 个字符。 以 -10 的起始偏移量调用substr()
将确保保留最后 10 位数字。 (演示)
echo substr(preg_replace('/\D+/', '', $string), -10);
作为旁注,您应该使用准备好的语句与您的数据库进行交互,而不是依赖可能存在漏洞的转义。
将 str_replace 与要删除的字符数组一起使用。
$str = "(111)222-3333 111-222-3333 111.222.3333 +11112223333";
echo str_replace(["(", ")", "-", "+", "."], "", $str);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.