please help me modify this regex

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

Moderator: General Moderators

Post Reply
kc11
Forum Commoner
Posts: 73
Joined: Mon Sep 27, 2010 3:26 pm

please help me modify this regex

Post by kc11 »

Hello,

I am using the following regex to parse text for phone numbers:

Code: Select all

  $text="bbbbbbbbbbbbbbbbbbbbb (123) 456-7810 hhhhhhhhhhhhhhh";
    $all_phones='';
    preg_match_all("/\(?  (\d{3})?  \)?  (?(1)  [\-\s] ) \d{3}-\d{4}/x",$text, $all_phones);
              

This works for (123) 456-7810, but not (123)456-7810.

Can anyone show me how to make it work for both?

Thanks in advance,

KC
User avatar
ragax
Forum Commoner
Posts: 85
Joined: Thu Dec 15, 2011 1:40 pm
Location: Nelson, NZ

Re: please help me modify this regex

Post by ragax »

Hi kc,

Sure!
You need a question mark after the [\-\s]
Without it, it says "if we've matched 3 digits, then match a space or a dash.
Cleaned up, it could look like this:

Code: Select all

$string='(123) 456-7810 (123)456-7810";';
$regex=',\(?(\d{3})?\)?(?(1)[-\s]?)\d{3}-\d{4},';
preg_match_all($regex,$string,$m);
var_dump($m[0]);
Output:
array(2) { [0]=> string(14) "(123) 456-7810" [1]=> string(13) "(123)456-7810" }

Also, if you don't need to use the area code on its own, then I might bring the parentheses inside Group 1: change the pattern line to
$regex=',(\(?\d{3}?\)?)(?(1)[-\s]?)\d{3}-\d{4},';

Let me know if you have any questions!
kc11
Forum Commoner
Posts: 73
Joined: Mon Sep 27, 2010 3:26 pm

Re: please help me modify this regex

Post by kc11 »

Thank you Rajax,

You've got it working!

Best regards,

KC
User avatar
ragax
Forum Commoner
Posts: 85
Joined: Thu Dec 15, 2011 1:40 pm
Location: Nelson, NZ

Re: please help me modify this regex

Post by ragax »

You're welcome, KC, thanks for letting me know it works for you.
Wishing you a fun weekend.
:)
Post Reply