[英]PHP - Validate phone number
I need to validate phone number in PHP, but the example below do not work. 我需要在PHP中验证电话号码,但以下示例不起作用。
$phone = '(123) 458-1542';
if(preg_match("/^([0-9]{3})-[0-9]{3}-[0-9]{4}$/", $phone)) {
}
Add a space and escape the round brackets: 添加一个空格并避开圆括号:
^\([0-9]{3}\)[- ][0-9]{3}-[0-9]{4}$
^^ ^^^^^^
I added a character class [- ]
just in case there can be either a space or a hyphen after the area code. 我添加了字符类
[- ]
,以防区号后可以有空格或连字符。 Parentheses must be escaped in order to be treated as literal symbols and not as a grouping construct . 必须将括号转义才能将其视为文字符号而不是分组构造 。
$phone = '(123) 458-1542';
if(preg_match('~^\([0-9]{3}\)[- ][0-9]{3}-[0-9]{4}$~', $phone)) {
echo "Matched: $phone";
}
Use this regex: 使用此正则表达式:
^\(*\+*[1-9]{0,3}\)*-*[1-9]{0,3}[-. /]*\(*[2-9]\d{2}\)*[-. /]*\d{3}[-. /]*\d{4} *e*x*t*\.* *\d{0,4}$
Following phone numbers have been tested: 以下电话号码已经过测试:
1-234-567-8901
1-234-567-8901 x1234
1-234-567-8901 ext1234
1 (234) 567-8901
1.234.567.8901
1/234/567/8901
12345678901
1-234-567-8901 ext. 1234
(+351) 282 433 5050
Example: http://www.regexr.com/3bp4b 例如: http : //www.regexr.com/3bp4b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.