Joanne DeBiasa
Joanne DeBiasa

Reputation: 15

Simple phone number regex for php

I've been looking for a simple phone number regex that will match just this format: (XXX) XXX-XXXX <---with the parentheses and the space after them required

For the life of me, I can't figure out why this wont work (This was one that I tried making myself and have been tinkering with for hours):

^[\(0-9\){3} [0-9]{3}-[0-9]{4}$

I've looked everywhere online for a regex with that particular format matching to no avail. Please help?

Upvotes: 0

Views: 16273

Answers (6)

user3251285
user3251285

Reputation: 163

EDITED ^\(?\d{3}\)?\s?\-?\d{3}\s?\-?\d{4}$

in Php works for the following

(999) 999 9999

(999) 999-9999

(999) 999-9999

999 999 9999

999 999-9999

999-999-9999

Upvotes: 0

Jason Lau
Jason Lau

Reputation: 1

/(\(\d{3}+\)+ \d{3}+\-\d{4}+)/ (000) 000-0000

/(\d{3}+\-\d{3}+\-\d{4}+)/ 000-000-0000

Upvotes: 0

bukart
bukart

Reputation: 4906

here's a working one

/^\(\d{3}\) \d{3}-\d{4}\s$/


the problems with your's:

to match digits just use \d or [0-9] (square brackets are needed, you've forgot them in first occurence) to match parenthesis use \( and \). They have to be escaped, otherwise they will be interpreted as match and your regex won't compile

Upvotes: 1

user1726343
user1726343

Reputation:

The problems you are having are:

  1. You need to escape special characters (like parentheses) with a backslash, like this: \(
  2. You have an unclosed square bracket at the beginning.

Otherwise, you're good!

Upvotes: 1

Marc B
Marc B

Reputation: 360872

[] define character classes. e.g. "at this one single character spot, any of the following can match". Your brackets are misaligned:

^[\(0-9\){3} [0-9]{3}-[0-9]{4}$
 ^---no matching closer

e.g.

^[0-9]{3} [0-9]{3}-[0-9]{4}$

would be closer to what you want.

Upvotes: 0

Anirudh Ramanathan
Anirudh Ramanathan

Reputation: 46778

The following regex works

^\(\d{3}\) \d{3}-\d{4}$

^ = start of line
\( = matches parenthesis open
\d = digit (0-9)
\) = matches parenthesis close

Upvotes: 6

Related Questions