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);

preferences:
25.43 ms | 407 KiB | 5 Q