Regex 10 digit phone number help

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
dhui
Forum Newbie
Posts: 14
Joined: Mon May 10, 2010 1:42 pm

Regex 10 digit phone number help

Post 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!
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Regex 10 digit phone number help

Post 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]
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
dhui
Forum Newbie
Posts: 14
Joined: Mon May 10, 2010 1:42 pm

Re: Regex 10 digit phone number help

Post 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!
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Regex 10 digit phone number help

Post 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]
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Post Reply