PHP Developers Network
http://forums.devnetwork.net/

Split string and consolidate into an array
http://forums.devnetwork.net/viewtopic.php?f=38&t=144141
Page 1 of 1

Author:  jonnyenglish89 [ Sun Aug 27, 2017 8:02 am ]
Post subject:  Split string and consolidate into an array

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?

Author:  requinix [ Sun Aug 27, 2017 9:02 am ]
Post subject:  Re: Split string and consolidate into an array

A regex probably won't get you much more than a plain explode() can.

explode on comma+space, then count the values.

Author:  jonnyenglish89 [ Sun Aug 27, 2017 2:28 pm ]
Post subject:  Re: Split string and consolidate into an array

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?

Author:  requinix [ Mon Aug 28, 2017 1:16 am ]
Post subject:  Re: Split string and consolidate into an array

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
Syntax: [ Download ] [ Hide ]
$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);

Page 1 of 1 All times are UTC - 5 hours
Powered by phpBB® Forum Software © phpBB Group
http://www.phpbb.com/