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?
Data:
~0
11111111
~1
222222222
~2
3333333333
~end
~0
aaaaaaaaaaa
~1
bbbbbbbbbb
~2
cccccccccc
~3
ddddddddddd
~end
~0
yyyyyyyyyyy
xxxxxxxx
ffffffffff
~1
rrrrrrrrrrrr
~end
I need it like this:
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
)
),
)
My code (Fail):
$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;
}
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.For a regex solution, start by exploding on
~end
to break the main text into sections, thenpreg_match_all
on the sections to find lines that meet your conditions.(?!~)
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.