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);
Output for 5.6.0 - 5.6.26, 7.0.0 - 7.0.20, 7.1.0 - 7.1.25, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.28, 8.4.1 - 8.4.14, 8.5.0 - 8.5.1
array(3) { ["category1"]=> array(3) { [0]=> string(7) "subcat1" [1]=> string(7) "subcat2" [2]=> string(7) "subcat3" } ["category2"]=> array(2) { [0]=> string(7) "subcat1" [1]=> string(7) "subcat2" } ["category3"]=> array(2) { [0]=> string(7) "subcat1" [1]=> string(7) "subcat3" } }
Output for 8.4.15
/bin/php-8.4.15: /usr/lib/libm.so.6: version `GLIBC_2.38' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libm.so.6: version `GLIBC_2.35' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libc.so.6: version `GLIBC_2.34' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libc.so.6: version `GLIBC_2.38' not found (required by /bin/php-8.4.15)
Process exited with code 1.

preferences:
198.32 ms | 407 KiB | 5 Q