Here are two ways to generate your desired multidimensional array of key-value pairs with preg_split()
...
(Demo)
Approach #1: Split on =
or space followed by 1 or more word characters then a =
var_export(array_chunk(preg_split('~=| (?=\w+=)~', $text), 2));
Approach #2: Split on each key, include leading&training characters in match, retain only keys & values
var_export(array_chunk(preg_split('~ ?(\w+)=~', $text, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE), 2));
Output: (from either)
array (
0 =>
array (
0 => 'key1',
1 => 'value 1',
),
1 =>
array (
0 => 'key2',
1 => 'value 2',
),
2 =>
array (
0 => 'key3',
1 => 'val 3',
),
)
preg_split()
can only return a single dimensional array (in this case, key
, val
, key
, val
, ...), so array_chunk()
is used to generate the desired two-elements-per-subarray structure.