0

I have the following text:

Main: (555) 551-0341 Pharmacy: (555) 551-4304

I'd like to separate this out to two variables:

 $main = (555) 551-0341
 $pharm = (555) 551-4304

I'm not familiar with regular expressions enough to move around these words. Any help would be awesome!

hakre
  • 193,403
  • 52
  • 435
  • 836
Ken J
  • 4,312
  • 12
  • 50
  • 86
  • 1
    Umm.. Excuse me for pointing out the obvious but you could just write `$main = "(555) 551-0341"; $pharm = "(555) 551-4304"` ... ? – George Nov 07 '12 at 15:30
  • He is parsing a text or smth and he wants to process the info man... – ka_lin Nov 07 '12 at 15:33
  • * See also [Open source RegexBuddy alternatives](http://stackoverflow.com/questions/89718/is-there) and [Online regex testing](http://stackoverflow.com/questions/32282/regex-testing) for some helpful tools, or [RegExp.info](http://regular-expressions.info/) for a nicer tutorial. – mario Nov 07 '12 at 15:34
  • You could check out http://stackoverflow.com/questions/3357675/validating-us-phone-number-with-php-regex – ka_lin Nov 07 '12 at 15:41
  • Thanks for all the info! – Ken J Nov 07 '12 at 15:54

2 Answers2

2

You can achieve this very easily.

$string = 'Main: (555) 551-0341 Pharmacy: (555) 551-4304';
preg_match_all('/(?P<name>[a-zA-Z]+): (?P<phone>[\(\)\s0-9-]{10,})/i', $string, $m);
$data  = array_combine($m['name'], $m['phone']);

Now $data['main'] contains (555) 551-0341 and so do $data['pharmacy']. Its recommended to keep these values in an array.

If you really want to put those variable in global namespace use extract funciton.

extract($data);

Demonastration

Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
0

It makes not much sense to extract the variable names out of the string - if the string changes, the names would change, too. Therefore you need to make the regular expression pretty fitting to this specific case so not to introduce unexpected variables.

Also the variables you intend to extract need initialization before doing the extraction.

Some example code (Demo):

$string = 'Main: (555) 551-0341 Pharmacy: (555) 551-4304';

$main = $pharmacy = null;

foreach(
    preg_match_all(
        '/(Main|Pharmacy): (\(555\) 551-\d{4})/i', $string, $m, PREG_SET_ORDER
    )
    ? $m
    : []
    as $p
) {
    $p[1]  = strtolower($p[1]);
    $$p[1] = $p[2];
}

var_dump($main, $pharmacy);

Example output:

string(14) "(555) 551-0341"
string(14) "(555) 551-4304"
hakre
  • 193,403
  • 52
  • 435
  • 836