Page 1 of 1

please help me modify this regex

Posted: Fri Mar 23, 2012 9:23 pm
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

Re: please help me modify this regex

Posted: Sat Mar 24, 2012 12:12 am
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!

Re: please help me modify this regex

Posted: Sat Mar 24, 2012 9:39 am
by kc11
Thank you Rajax,

You've got it working!

Best regards,

KC

Re: please help me modify this regex

Posted: Sat Mar 24, 2012 2:34 pm
by ragax
You're welcome, KC, thanks for letting me know it works for you.
Wishing you a fun weekend.
:)