I need to validate phone number in PHP, but the example below do not work.
$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}$
^^ ^^^^^^
See the demo
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 .
PHP demo :
$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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.