1

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)) {

}
2
  • there is () in $phone Commented Apr 19, 2016 at 10:57
  • Is the number in your example supposed to be valid or invalid? How should we know? If you need to build / check / validate regex, use a tool for that, for example: regex101.com Commented Apr 19, 2016 at 11:05

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Best answer so far. The others are too strict with spaces/hyphens/brackets etc
3

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";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.