[英]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.