【问题标题】:How to preg_split square brackets and group them into array [duplicate]如何preg_split方括号并将它们分组到数组中[重复]
【发布时间】:2019-02-27 13:52:10
【问题描述】:

我有一个要在 PHP 中读取的 .ini 文件,并希望将它们转换为多维数组。

输入

[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)并转换为我的数组的键。

【问题讨论】:

    标签: php arrays regex ini preg-split


    【解决方案1】:

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

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

    【讨论】:

    • 我认为 parse_ini_file() 完全符合您的需要
    • 感谢@Darthur,您的回答有助于解决我的问题!
    • 这实际上是@Mureinik 的回答,我只是在批准他的消息,因为他设法在我之前几秒钟发布了它:D 你还应该将他的回答标记为已接受
    • 感谢@Mureinik 的解决方案!
    猜你喜欢
    • 2019-08-26
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 2014-10-18
    相关资源
    最近更新 更多