【发布时间】:2023-03-04 20:31:01
【问题描述】:
我需要将数据按块传递给数组,我该怎么做?我需要使用正则表达式吗?我的脚本给了我错误,因为我无法按照我的意愿将它分开。有人有什么想法吗?
数据:
~0
11111111
~1
222222222
~2
3333333333
~end
~0
aaaaaaaaaaa
~1
bbbbbbbbbb
~2
cccccccccc
~3
ddddddddddd
~end
~0
yyyyyyyyyyy
xxxxxxxx
ffffffffff
~1
rrrrrrrrrrrr
~end
我需要这样的:
Array (
[0] => Array
(
[0] => 11111111
[1] => 222222222
[2] => 3333333333
)
),
[1] => Array
(
[0] => aaaaaaaaaaa
[1] => bbbbbbbbbb
[2] => cccccccccc
[3] => ddddddddddd
)
),
[2] => Array
(
[0] => yyyyyyyyyyy
xxxxxxxx
ffffffffff
[1] => rrrrrrrrrrrr
)
),
)
我的代码(失败):
$texto = "~0
11111111
~1
222222222
~2
3333333333
~end
~0
aaaaaaaaaaa
~1
bbbbbbbbbb
~2
cccccccccc
~3
ddddddddddd
~end
~0
yyyyyyyyyyy
xxxxxxxx
ffffffffff
~1
rrrrrrrrrrrr
~end";
preg_match_all("/(?ms)^~0.*?~end/", $texto, $coincidencias);
foreach ( $coincidencias[0] as $bloque ){
preg_match_all("/\~.*\n/", $bloque, $sub_bloques);
$hola[] = $sub_bloques;
}
【问题讨论】:
-
我不确定我是否正确理解了这些要求,您能确认一下吗? "每个非空行不以字符 ~ 开头,应该是数组中的一个条目"
-
@Dragos 从 "~0" 到 "~end" 是一个块(现在是 3 个块),每个块的文本在 ~0、~1、~2 到数组位置(只有文本)
-
我宁愿分两步工作:1.
$level1 = explode('~end', $data)2.foreach ($level1 as $subItem) { $matches = preg_match_all('^(\w*)$', $subItem) } -
@Dragos print_r($matches) => 0
标签: php arrays regex multidimensional-array preg-match-all