3v4l.org

run code in 300+ PHP versions simultaneously
<?php $str = <<<STR category1_subcat_1 category1_subcat_2 category1_subcat_3 category2_subcat_1 category2_subcat_2 category3_subcat_1 category3_subcat_3 STR; // Explode the string, with a newline as the delimiter $lines = explode("\n", $str); // Init the category array $cats = []; // iterate over the lines foreach($lines as $currentLine) { // Match category{DIGIT} using regular exp preg_match("/category[0-9]/", $currentLine, $match); // Remove the $match from the current line $currentLine = str_replace($match[0], "", $currentLine); // Push the element to the categories array, and also remove the // the underscores (_) $cats[$match[0]][] = str_replace("_", "", $currentLine); } var_dump($cats);

preferences:
163.25 ms | 407 KiB | 5 Q