如何preg_split方括号并将其分组为数组

时间:2018-09-24 04:35:40

标签: php arrays regex ini preg-split

我有一个.ini文件,可以用PHP读取,并希望将它们转换为多维数组。

输入

[101]
DestName=Person A
dstaddr=+880071268
smbody=This Is Testing 1
response=http://localhost/reply.php
[102]
DestName=Person B
dstaddr=+890071268
smbody=This Is Testing 2
[103]
.
.
.

我想使用正则表达式preg_split从中获得一个数组:

预期产量

[
 "101": [
     DestName: "Person A"
     dstaddr: "+880071268"
     response: "http://localhost/reply.php"
     smbody: "This Is Testing 1"
    ]
 "102": [
     DestName: "Person B"
     dstaddr: "+890071268"
     smbody: "This Is Testing 2"
    ]
]

我从这里阅读了一些答案,并尝试了如下代码以获取其他输出。

$num = preg_split("#\[[^\]]+\]\r\n#", $fread, NULL, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

foreach ($num as $skey => $str){
    foreach (explode("\r\n", $str) as $key => $line) {
        $l = explode('=', trim($line));
        if (isset($l[1])){
            $arr[$skey][$l[0]] = $l[1];
        }
    }
}

我的输出

[
 0: [
     DestName: "Person A"
     dstaddr: "+880071268"
     response: "http://localhost/reply.php"
     smbody: "This Is Testing 1"
    ]
 1: [
     DestName: "Person B"
     dstaddr: "+890071268"
     smbody: "This Is Testing 2"
    ]
]

请注意,我无法获取方括号内的值(例如[101]中的101),并不能将其转换为数组的键。

1 个答案:

答案 0 :(得分:2)

只使用内置的parse_ini_file会容易得多:

$result = parse_ini_file("myfile.ini", true)