duanpuchun5275 2017-05-30 21:18
浏览 84
已采纳

使用正则表达式从字符串中获取匹配模式的最短方法

I have pretty long string to parse, that looks like that (part of it)

$string = 'FIRM_ID = MC0356400000; TAG = EQTV; CURR_CODE = SUR; CLIENT_CODE = FR334; LIMIT_KIND = 1; OPEN_BALANCE = 4822.84; OPEN_LIMIT = 0.00; LEVERAGE = 0;'

I need to get values for php variables from that string, which I do with preg_match:

 preg_match("/FIRM_ID = (.*?);/", $string, $m);
 $firm_id = trim($m[1]);

 preg_match("/CLIENT_CODE = (.*?);/", $string, $m);
 $client_code = trim($m[1]);

... and so on

I was wondering is there a way to do the same in one line? May be with preg_replace or other functions, so I would not have to declare $m variable first and then take out from that [1] element.

So the code supposed to look like

 $firm_id = somefunction($string);
 $client_code = somefunction($string);

Its not practical question, more theoretical. I know how to get result that I need, I want to know if there is a simpler and more elegant way.

Thanks.

  • 写回答

3条回答 默认 最新

  • dongyan5239 2017-05-30 21:26
    关注

    Match and capture key-value pairs and then combine into an array:

    $re = '/(\w+)\s*=\s*([^;]*)/';
    $str = 'FIRM_ID = MC0356400000; TAG = EQTV; CURR_CODE = SUR; CLIENT_CODE = FR334; LIMIT_KIND = 1; OPEN_BALANCE = 4822.84; OPEN_LIMIT = 0.00; LEVERAGE = 0;';
    preg_match_all($re, $str, $matches);
    print_r(array_combine($matches[1],$matches[2]));
    

    See the PHP demo, result:

    Array
    (
        [FIRM_ID] => MC0356400000
        [TAG] => EQTV
        [CURR_CODE] => SUR
        [CLIENT_CODE] => FR334
        [LIMIT_KIND] => 1
        [OPEN_BALANCE] => 4822.84
        [OPEN_LIMIT] => 0.00
        [LEVERAGE] => 0
    )
    

    The regex is

    /(\w+)\s*=\s*([^;]*)/
    

    See is demo online.

    Details:

    • (\w+) - Group 1: one or more word chars
    • \s*=\s* - a = enclosed with optional whitespace(s)
    • ([^;]*) - Group 2: zero or more chars other than ;.

    To "initialize" the variables each at a time, you may use a

    $var_name = 'FIRM_ID';
    $re = '/' . $var_name . '\s*=\s*\K[^;]*/';
    $str = 'FIRM_ID = MC0356400000; TAG = EQTV; CURR_CODE = SUR; CLIENT_CODE = FR334; LIMIT_KIND = 1; OPEN_BALANCE = 4822.84; OPEN_LIMIT = 0.00; LEVERAGE = 0;';
    preg_match($re, $str, $m);
    print_r($m);
    

    See the PHP demo.

    The \K is the match reset operator that omits all text matched so far within the current match iteration.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作