3v4l.org

run code in 300+ PHP versions simultaneously
<?php //Input string (Ignore the syntax editor, 3v4l's parser can't see that it's a valid HEREDOC string) $str = <<< END 2x egg 2 - carrot cabbage 1x potato 3xyx&& asd - --()(--=) yams 6 mangos 7 whatevers lots of words and stuff, but really though 6 of your finest grapes END; $lines = explode("\n", $str); //Split the input into lines for parsing $ingredients = Array(); //Ready the ingredients array for populating foreach($lines as $line) { $matches = Array(); if(!preg_match("/^.*?(\d+).*?(\S+)(\s+)?$/", $line, $matches)) //Get the number (\d+) from the start (^) of the line and the ingredient name (\S+) from the end ($) of the string array_push($ingredients, Array(1, $line)); //If we can't find the number or ingredient that way just assume it's 1 of whatever the line has in it else array_push($ingredients, Array(intval($matches[1]), $matches[2])); //Otherwise add it to the array with the correct amount and name } var_dump($ingredients);
Output for 5.4.0 - 5.4.45, 5.5.0 - 5.5.38, 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.34, 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.25, 8.4.1 - 8.4.12
array(8) { [0]=> array(2) { [0]=> int(2) [1]=> string(3) "egg" } [1]=> array(2) { [0]=> int(2) [1]=> string(6) "carrot" } [2]=> array(2) { [0]=> int(1) [1]=> string(7) "cabbage" } [3]=> array(2) { [0]=> int(1) [1]=> string(6) "potato" } [4]=> array(2) { [0]=> int(3) [1]=> string(4) "yams" } [5]=> array(2) { [0]=> int(6) [1]=> string(6) "mangos" } [6]=> array(2) { [0]=> int(7) [1]=> string(9) "whatevers" } [7]=> array(2) { [0]=> int(6) [1]=> string(6) "grapes" } }

preferences:
145.5 ms | 410 KiB | 5 Q