简体   繁体   中英

Assign Phone Numbers to their Lables with a Regular Expression

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!

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM