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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?