Preg匹配花括号外的所有逗号

时间:2018-08-14 01:43:41

标签: php preg-match-all

我有一个字符串:

<b>08-14-2018 09:24:09</b>,192.168.0.1,{"i":"2018-001370","ln":"FIRST","fn":"TEST","a":"570.00","d":"08\/14\/2018 09:23:00","ca":"550.00","ch":"20.00","chi":"s"},{"terapay_response":{"code":-106,"description":"Missing Check Amount Or Check Info"}}

我想匹配花括号外的所有逗号。

我想要的输出是:

[0] : <b>08-14-2018 09:24:09</b>
[1] : 192.168.0.1
[2] : {"i":"2018-001370","ln":"FIRST","fn":"TEST","a":"570.00","d":"08\/14\/2018 09:23:00","ca":"550.00","ch":"20.00","chi":"s"}
[3] : {"terapay_response":{"code":-106,"description":"Missing Check Amount Or Check Info"}}

我尝试过:

preg_match_all("/\((?:[^{}]|(?R))+\)|[^{},\s]+/", $line, $out);

但是输出是不同的:

[0] : "<b>08-14-2018"
[1] : "09:24:09</b>"
[2] : "192.168.0.1"
[3] : ""i":"2018-001370""
[4] : ""ln":"FIRST""
[5] : ""fn":"TEST""
[6] : ""a":"570.00""
[7] : ""d":"08\/14\/2018"
[8] : "09:23:00""
[9] : ""ca":"550.00""
[10] : ""ch":"20.00""
[11] : ""chi":"s""
[12] : ""terapay_response":"
[13] : ""code":-106"
[14] : ""description":"Missing"
[15] : "Check"
[16] : "Amount"
[17] : "Or"
[18] : "Check"
[19] : "Info""

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用此正则表达式:

/,(?![^{]*})/

将找到不在,(基于此answer)内的{}来用preg_split分割字符串:

$str = '<b>08-14-2018 09:24:09</b>,192.168.0.1,{"i":"2018-001370","ln":"FIRST","fn":"TEST","a":"570.00","d":"08\/14\/2018 09:23:00","ca":"550.00","ch":"20.00","chi":"s"},{"terapay_response":{"code":-106,"description":"Missing Check Amount Or Check Info"}}';
print_r(preg_split('/,(?![^{]*})/', $str));

输出:

数组

(
    [0] => 08-14-2018 09:24:09
    [1] => 192.168.0.1
    [2] => {"i":"2018-001370","ln":"FIRST","fn":"TEST","a":"570.00","d":"08\/14\/2018 09:23:00","ca":"550.00","ch":"20.00","chi":"s"}
    [3] => {"terapay_response":{"code":-106,"description":"Missing Check Amount Or Check Info"}}
)