Split string and consolidate into an array

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
jonnyenglish89
Forum Newbie
Posts: 2
Joined: Sun Aug 27, 2017 7:53 am

Split string and consolidate into an array

Post 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?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Split string and consolidate into an array

Post by requinix »

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

explode on comma+space, then count the values.
jonnyenglish89
Forum Newbie
Posts: 2
Joined: Sun Aug 27, 2017 7:53 am

Re: Split string and consolidate into an array

Post 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?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Split string and consolidate into an array

Post 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);
Post Reply