I am trying to use regex in PHP to parse a string and make an array. Here is my attempt:
function parseItemName($itemname) {
// Given item name like "2 of #222001." or "3 of #222001; 5 of #222002."
// Return array like (222001 => 2) or (222001 => 3, 222002 => 5)
preg_match('/([0-9]?) of #([0-9]?)(.|;\s)/', $itemname, $matches);
return $matches;
}
Calling the function with
print_r(parseItemName("3 of #222001; 5 of #222002."));
returns
Array ( [0] => 3 of #22 [1] => 3 [2] => 2 [3] => 2 )
Does anyone know how to make this work? I assume that preg_match() is not the best way to do this, but I’m not sure what else to try. I appreciate any ideas. Thank you!
Aside from the adjustment to your regex pattern, you want to be using
preg_match_allwith thePREG_SET_ORDERflag set to make things simpler.This will return a
$matchesarray arranged like so:The below example function now loops through all of the matches, and constructs a new array, using the second match as the key, and the first match as the value.
The output that is dumped will look like this: