如何解析为字符串到多维数组(正则表达式?) [英] How to parse to string to multidimensional array (regex?)
问题描述
我需要按块将数据传递到数组,我该怎么做?我需要使用正则表达式吗?我的脚本给了我错误,因为我无法根据需要将其分开。有人有什么想法吗?
I need to pass the data to an array by blocks, how can I make this? Do I need to use regex? My script gives me errors because I can not separate it as I wish. Does anyone have any ideas?
数据:
~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;
}
推荐答案
这里是一种非正则表达式方式:将字符串分成几行,然后遍历它们。检查您指定的条件,并在满足条件的情况下将每一行添加到子数组中。然后,当到达〜end
行时,将子数组追加到主数组中。
Here is one non-regex way: split the string into lines and iterate over them. Check for the conditions you've specified and add each line to a sub-array if it meets the conditions. Then when you get to an ~end
line, append the sub-array to the main array.
$sub_bloques = [];
$hola = [];
foreach(array_map('trim', explode("\n", $texto)) as $line) {
if ($line && substr($line, 0, 1) !== '~') {
$sub_bloques[] = $line;
}
if ($line == '~end') {
$hola[] = $sub_bloques;
$sub_bloques = [];
}
}
对于正则表达式解决方案,首先在〜end
上展开以将正文分成多个部分,然后在这些部分上 preg_match_all
查找符合条件的行。
For a regex solution, start by exploding on ~end
to break the main text into sections, then preg_match_all
on the sections to find lines that meet your conditions.
foreach (explode('~end', $texto, -1) as $section) {
preg_match_all('/\n *(?!~)(\w+)/', $section, $matches);
if ($matches[1]) $result[] = $matches[1];
}
(?!〜)
是排除在后的〜
开头的行。也许有一种方法可以用一个很酷的正则表达式来完成整个工作,但是我并不那么擅长。
(?!~)
is a a negative lookbehind to exclude lines that start with ~
. Maybe there's some way to do the whole thing with one big cool regex, but I'm not that good at it.
这篇关于如何解析为字符串到多维数组(正则表达式?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!