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?
Split string and consolidate into an array
Moderator: General Moderators
-
- Forum Newbie
- Posts: 2
- Joined: Sun Aug 27, 2017 7:53 am
-
- Forum Newbie
- Posts: 2
- Joined: Sun Aug 27, 2017 7:53 am
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?
Should I move the topic to the general php chat?
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
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);