简体   繁体   English

使用正则表达式将电话号码分配给其Lable

[英]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'] . 现在$data['main']包含(555) 551-0341$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 funciton。

extract($data);

Demonastration 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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