PHP Developers Network

A community of PHP developers offering assistance, advice, discussion, and friendship.
 
Loading
It is currently Fri Nov 16, 2018 9:56 am

All times are UTC - 5 hours




Post new topic Reply to topic  [ 4 posts ] 
Author Message
PostPosted: Fri Mar 23, 2012 9:23 pm 
Offline
Forum Commoner

Joined: Mon Sep 27, 2010 3:26 pm
Posts: 73
Hello,

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

Syntax: [ Download ] [ Hide ]
  $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


Top
 Profile  
 
PostPosted: Sat Mar 24, 2012 12:12 am 
Offline
Forum Commoner
User avatar

Joined: Thu Dec 15, 2011 2:40 pm
Posts: 85
Location: Nelson, NZ
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:

Syntax: [ Download ] [ Hide ]
$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!


Top
 Profile  
 
PostPosted: Sat Mar 24, 2012 9:39 am 
Offline
Forum Commoner

Joined: Mon Sep 27, 2010 3:26 pm
Posts: 73
Thank you Rajax,

You've got it working!

Best regards,

KC


Top
 Profile  
 
PostPosted: Sat Mar 24, 2012 2:34 pm 
Offline
Forum Commoner
User avatar

Joined: Thu Dec 15, 2011 2:40 pm
Posts: 85
Location: Nelson, NZ
You're welcome, KC, thanks for letting me know it works for you.
Wishing you a fun weekend.
:)


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 4 posts ] 

All times are UTC - 5 hours


Who is online

Users browsing this forum: No registered users and 4 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
Powered by phpBB® Forum Software © phpBB Group