在PHP中解析方括号和嵌套括号

时间:2017-01-12 15:21:37

标签: php regex parsing

我想请求帮助。

我有这个语法

[86855,[[6615663,"Name 1 [GBR]","Name 2 [RUS]",86855,"2017-01-13T09:30:00.0000000",[[16942762,0,,,,1],[16942763,738,,,,2],[16942869,741,,,,1],[16942870,113,,,,1],[16944801,759,,,1],[16944804,759,,,2],[16943142,740,,,,1],[16943144,743,,,,5],[16943145,744,,,,5]],[[25262023,758],[25259130,748],[25259131,749],[25258578,739]],,,,,80104,194132,-1,-1,0,0,0,0,"Sport","League",6,22,0,null,"10890680"],[6614528,"Name 1 [SRB]","Name 2 [LUX]",86855,"2017-01-13T05:00:00.0000000",[[16939629,741,,,,1],[16939630,113,,,,1],[16939632,759,,,1],[16939634,759,,,2],[16939069,0,,,,1],[16939070,740,,,,1],[16939071,738,,,,2],[16942414,743,,,,5],[16942415,744,,,,5]],[[25257607,748],[25257608,749],[25257609,758],[25253011,739]],,,,,1610,48295,-1,-1,0,0,0,0,"Sport","League",6,22,0,null,"10888520"]],[[25138199,8,,,,"2017-01-13T05:00:00.0000000",,,,0,null,null]]],[]

我想从输出中获取数组。像这样的东西

[0] => 86855
  [0] =>
     [0] => 6615663
     [1] => "Name 1 [GRB]"
     etc...
  [1] =>
     [0] => 6614528
     [1] => "Name 1 [SRB]"
     etc...

是否可以通过任何注册表执行此操作。以某种方式表达或解析?

谢谢:)

1 个答案:

答案 0 :(得分:0)

您的数据看起来像一个用字符串括起来的数组。您可以使用eval构建数组,但出于安全原因,您需要检查您的字符串是否仅包含允许的项(即:数值,字符串,空项,null和数组。换句话说,没有可执行文件代码),如果格式良好。

第二次,您需要将“empty”值更改为PHP解析器能够识别的值。

示例:

$pattern = '~
    (?(DEFINE)                         # tokens definitions
        (?<quoted> " [^"\\\\]*+ (?s:\\\\.[^"\\\\]*)*+ " )
        (?<num> -? \d+ (?: \. \d*)? | \. \d+ )
        (?<item> \g<quoted> | \g<num> | \g<array> | null | \s* )
        (?<itemList> \g<item> (?: \s* , \s* \g<item> )* )
        (?<array> \[ \s* \g<itemList> \s* ] )
    )

    \A \s* \g<itemList> \s* \z         # main pattern
~xi';

if (preg_match($pattern, $str)) {
    $expr = preg_replace('~"[^"\\\\]*+(?s:\\\\.[^"\\\\]*)*+"(*SKIP)(*F)|,\s*(?=,)~S', ',null', $str);
    $expr = '$result=[' . $expr . '];'; 
    eval($expr);
    print_r($result);
} else throw new Exception('Bad format');