Page 1 of 1
Split string and consolidate into an array
Posted: Sun Aug 27, 2017 8:02 am
by jonnyenglish89
Hey guys,
is it possible to consolidate a string like this:
Octane Optimized, Yurich's Nexus, Ember of Kytos, Aerial Ocelot, Ember of Kytos #2, Aerial Ocelot #5, Ember of Kytos
Into this:
{"Octane Optimized":"1","Yurich's Nexus ":"1","Ember of Kytos":"4"," Aerial Ocelot":"6"}
With the help of regex in php? If it is, how would it be done?
Re: Split string and consolidate into an array
Posted: Sun Aug 27, 2017 9:02 am
by requinix
A regex probably won't get you much more than a plain explode() can.
explode on comma+space, then
count the values.
Re: Split string and consolidate into an array
Posted: Sun Aug 27, 2017 2:28 pm
by jonnyenglish89
thanks, I can use explode and count but I get stuck on “Ember of Kytos #2” and “Aerial Ocelot #5” - How would I add the #2 to Ember of Kytos and the #5 to Aerial Ocelot to get the correct values?
Should I move the topic to the general php chat?
Re: Split string and consolidate into an array
Posted: Mon Aug 28, 2017 1:16 am
by requinix
Ah, I totally missed that.
I take back what I said: regex might be better after all. But crafting a good regex could be a bit difficult so
Code: Select all
$string = "Octane Optimized, Yurich's Nexus, Ember of Kytos, Aerial Ocelot, Ember of Kytos #2, Aerial Ocelot #5, Ember of Kytos";
$counts = array();
preg_match_all('/(^|,)\s*(?P<card>([^#,]+(#(?!\d+(,|$)))?)+)(#(?P<count>\d+))?/', $string, $matches, PREG_SET_ORDER);
foreach ($matches as $card) {
$c = trim($card["card"]);
$counts[$c] = ($counts[$c] ?? 0) + (empty($card["count"]) ? 1 : $card["count"]);
}
print_r($counts);