[英]How to format mobile phone number with country code using regex
我一直在嘗試正確格式化電話號碼,以便至少所有國家/地區都可以使用。 我正在嘗試使用這種格式來接受盡可能多的區域 這是我的模式
$pattern = '^\+[0-9]?()[0-9](\s|\S)(\d[0-9]{9})$^';
該模式與這些格式匹配得很好,但是一旦我添加了一個帶有 3 位數字和空格的國家/地區代碼,它就會失敗
+441213315000
+1 2323214316
+2923432432432
我想匹配這種格式
+225 0546568022
不像我們的朋友。 我試圖修復你自己的模式:
^\+([0-9][0-9]?[0-9]?)(\ )?([0-9]{10})$
請注意,我已經從模式末尾刪除了 ^,因為它代表新行的開始!
這家伙是你的朋友:https://regex101.com/
祝你好運
用
^\+[0-9]{1,3} ?[0-9]{10}$
請參閱正則表達式證明。
解釋
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
\+ '+'
--------------------------------------------------------------------------------
[0-9]{1,3} any character of: '0' to '9' (between 1
and 3 times (matching the most amount
possible))
--------------------------------------------------------------------------------
? ' ' (optional (matching the most amount
possible))
--------------------------------------------------------------------------------
[0-9]{10} any character of: '0' to '9' (10 times)
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string
PHP:
preg_match('/^\+[0-9]{1,3} ?[0-9]{10}$/', $string)
JavaScript:
/^\+[0-9]{1,3} ?[0-9]{10}$/.test(string)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.