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条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程