Php 如何预分割方括号并将其分组到数组中
我有一个用PHP读取的.ini文件,我想把它们转换成多维数组 输入:Php 如何预分割方括号并将其分组到数组中,php,arrays,regex,ini,preg-split,Php,Arrays,Regex,Ini,Preg Split,我有一个用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] . . . [ "101": [ DestName: "Pe
[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]
.
.
.
[
"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"
]
]
[
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"
]
]
我想用正则表达式preg_split从中得到一个数组:
预期产出:
[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]
.
.
.
[
"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"
]
]
[
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"
]
]
我已经阅读了这里的一些答案,并尝试了下面的代码以获得其他输出
$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];
}
}
}
我的输出:
[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]
.
.
.
[
"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"
]
]
[
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()完全符合您的需要谢谢@Darthur,您的回答帮助解决了我的问题!这实际上是@Mureinik的答案,我只是批准他的消息,因为他在我之前几秒钟就发布了:D你也应该把他的答案标记为已接受感谢@Mureinik的解决方案!我同意,parse_ini_file()完全符合您的需要谢谢@Darthur,您的回答帮助解决了我的问题!这实际上是@Mureinik的答案,我只是批准他的消息,因为他在我之前几秒钟就发布了:D你也应该把他的答案标记为已接受感谢@Mureinik的解决方案!