如何 preg_split 方括号并将它们分组到数组中
How to preg_split square brackets and group them into array
我有一个 .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)并转换为我的数组的键。
使用内置的 parse_ini_file
:
会容易得多
$result = parse_ini_file("myfile.ini", true)
我有一个 .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)并转换为我的数组的键。
使用内置的 parse_ini_file
:
$result = parse_ini_file("myfile.ini", true)