3v4l.org

run code in 300+ PHP versions simultaneously
<?php // The first group to assign un-prefixed items to $firstGroup = 'MAKE'; // Every possible word grouping $wordList = ['ENGINE', 'MODEL', 'POWER', 'TORQUE', 'GEAR', 'DRIVE', 'YEAR']; // Test string $string = 'Audi MODEL 80 ENGINE 1.9 TDi POWER 90Hk TORQUE 202Nm GEAR man DRIVE 2wd YEAR 1996'; // Key/value of group name and values $groups = []; // Default to the first group $currentWord = $firstGroup; foreach (explode(' ', $string) as $word) { // Found a special word, reset and continue the hunt if (in_array($word, $wordList)) { $currentWord = $word; continue; } // Assign. The subsequent for loop could be removed by just doing string concatenation here instead $groups[$currentWord][] = $word; } // Optional, join each back into a string foreach ($groups as $key => $values) { $groups[$key] = implode(' ', $values); } var_dump($groups);
Output for 8.0.1 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.25, 8.4.1 - 8.4.12
array(8) { ["MAKE"]=> string(4) "Audi" ["MODEL"]=> string(2) "80" ["ENGINE"]=> string(7) "1.9 TDi" ["POWER"]=> string(4) "90Hk" ["TORQUE"]=> string(5) "202Nm" ["GEAR"]=> string(3) "man" ["DRIVE"]=> string(3) "2wd" ["YEAR"]=> string(4) "1996" }

preferences:
93.62 ms | 407 KiB | 5 Q