Page 1 of 1

Regex 10 digit phone number help

Posted: Mon May 24, 2010 9:54 am
by dhui
Trying to do a preg_match to check for 3 possible patterns for a phone number...not really familiar with regex but below is what I have as my regex...it doesn't work.

Code: Select all

'/\d{3}-\d{3}-\d{4}|\d{10}|\d{3}+\.\d{3}+\.\d{4}/'
there should be 3 valid patterns - xxx-xxx-xxxx, xxxxxxxxxx, and xxx.xxx.xxxx

Everytime I enter input...it only checks the middle 3 numbers for the right length and I can't figure out why.

Any help will be greatly appreciated!

Re: Regex 10 digit phone number help

Posted: Mon May 24, 2010 10:25 am
by AbraCadaver
Try:
[text]'/^\d{3}[-\.]?\d{3}[-\.]?\d{4}$/'

match at the beginning of the string (^) and match
three digits optionally (?) followed by - or .
followed by three digits and optionally (?) followed by - or .
followed by four digits
end of the string ($)[/text]

Re: Regex 10 digit phone number help

Posted: Mon May 24, 2010 10:48 am
by dhui
I tried your suggestion and it was definitely an improvement! The only thing was that way you did it, it allowed for xxx-xxx.xxxx or xxx.xxx-xxxx and I wanted to only allow the same type of separator for both. So either 2 hyphens, 2 dots, or no separators. Below is the solution I came up with based on your suggested changes and what I had originally...I checked it a few times and seems to be working now.

Code: Select all

/^\d{3}-\d{3}-\d{4}$|^\d{10}$|^\d{3}\.\d{3}\.\d{4}$/
Thanks!

Re: Regex 10 digit phone number help

Posted: Mon May 24, 2010 12:23 pm
by AbraCadaver
My bad:

[text]'/^\d{3}([-\.]?)\d{3}\1\d{4}$/'

The \1 is a back reference to the first capture group. So whatever was captured in the ( ) must appear where the \1 is placed.
[/text]