Extract US phone numbers from string

I am trying to extract only US phone numbers from a string.

I looked through web / SO but did not find a suitable solution for my needs.

Honestly, I have 2.5 years of experience in web programming, but I suck at RegEX.

That's just RegEX I wrote (\d{3}+\-\d{3}+\-\d{4}+)

but he only discovers 589-845-2889

Here are the phone numbers I want to extract.

 589-845-2889 (589)-845-2889 589.845.2889 589 845 2889 5898452889 (589) 845 2889 

Please tell me how I can achieve this skill in one Regex for PHP.

EDIT:

If you feel any other U.S. number format that the user can enter, indicate this as well and include it in RegEX.

PS:

I am actually trying to clear Craiglist, and the user may have posted his phone number in any possible format.

+7
php regex
source share
2 answers

In PHP (PCRE), you can use this regex based on conditional subpatterns :

 (\()?\d{3}(?(1)\))[-.\h]?\d{3}[-.\h]?\d{4} 

RegEx Demo

  • (\()? matches optional ( and commits it to group # 1
  • (?(1)\)) is a conditional pattern that corresponds to closure ) only if group # 1 is not zero, i.e. ( present to the left of the match.
+2
source share

Finally it works:

 ^(\((\d{3})\)|(\d{3}))[\s\-\.]?\d{3}[\s\-\.]?\d{4} 

checked in notepad ++

+1
source share

All Articles