PHP Developers Network

A community of PHP developers offering assistance, advice, discussion, and friendship.
 
Loading
It is currently Sat Nov 18, 2017 3:17 am

All times are UTC - 5 hours




Post new topic Reply to topic  [ 4 posts ] 
Author Message
PostPosted: Sun Aug 27, 2017 8:02 am 
Offline
Forum Newbie

Joined: Sun Aug 27, 2017 7:53 am
Posts: 2
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?


Top
 Profile  
 
PostPosted: Sun Aug 27, 2017 9:02 am 
Offline
Spammer :|
User avatar

Joined: Wed Oct 15, 2008 2:35 am
Posts: 6578
Location: WA, USA
A regex probably won't get you much more than a plain explode() can.

explode on comma+space, then count the values.


Top
 Profile  
 
PostPosted: Sun Aug 27, 2017 2:28 pm 
Offline
Forum Newbie

Joined: Sun Aug 27, 2017 7:53 am
Posts: 2
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?


Top
 Profile  
 
PostPosted: Mon Aug 28, 2017 1:16 am 
Offline
Spammer :|
User avatar

Joined: Wed Oct 15, 2008 2:35 am
Posts: 6578
Location: WA, USA
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);


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 4 posts ] 

All times are UTC - 5 hours


Who is online

Users browsing this forum: No registered users and 3 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
Powered by phpBB® Forum Software © phpBB Group