Faye D.
Faye D.

Reputation: 732

Split a string every second occurence of a delimiter with regex

I would need your help on this, as I'm not very good at regex expressions!

I want to split the following string at every second occurrence of "/"

Alien 3 / Argentina / Alien 3 / Brazil / Alien 3 / Croatia / Vetřelec 3 / Czech Republic / Vetřelec 3 / Czechoslovakia / Alien³ / Denmark / Tulnukas 3 / Estonia / Alien³ / France / Alien 3 / Germany / Άλιεν³: Η Τελική Αναμέτρηση / Greece / A végső megoldás: Halál / Hungary / Alien³ / Italy / Svešais³ / Latvia / Svetimas 3 / Lithuania / Alien³ / Mexico / Alien 3 / Peru / Obcy 3 / Poland / Alien 3 - A Desforra / Portugal / Alien 3 / Romania / Чужой 3 / Russia / Туђин 3 / Serbia / Votrelec 3 / Slovakia / Osmi potnik 3 / Slovenia / Alien³ / Spain / 異形3 / Taiwan / Чужий 3 / Ukraine / Alien³ / UK / Alien³ / USA / Alien 3 / Uruguay

Ending up to an array like this

Array ( [0] => Amelie / Argentina [1] => Amelie / Australia [2] => O Fabuloso Destino de Amélie Poulain / Brazil [3] => El fabuloso destino de Amelie Poulain / Chile [4] => Amelie / Croatia [5] => Amélie z Montmartru / Czech Republic [6] => Den fabelagtige Amélie fra Montmartre / Denmark [7] => Amélie / Finland [8] => Le Fabuleux Destin d'Amélie Poulain / France [9] => Die fabelhafte Welt der Amelie / Germany [10] => Αμελί / Greece [11] => Amélie csodálatos élete / Hungary [12] => Il favoloso mondo di Amélie / Italy [13] => Ameri / Japan [14] => Amelija iš Monmartro / Lithuania [15] => Amelie / Mexico [16] => Den fabelaktige Amélie fra Montmartre / Norway [17] => Amelie / Peru [18] => Amelia / Poland [19] => O Fabuloso Destino de Amélie / Portugal [20] => Amélie / Romania [21] => Амели / Russia [22] => Чудесна судбина Амелије Пулен / Serbia [23] => Amélia / Slovakia [24] => Amelie / Spain [25] => Amelie från Montmartre / Sweden [26] => 艾蜜莉的異想世界 / Taiwan [27] => Амелі / Ukraine [28] => Amélie / UK [29] => Amélie / USA [30] => Ameli / Uzbekistan [31] => Amélie / World-wide )

What I ended up to is simply

/(.* \/ .*) /

, which doesn't do what I want as it leaves the last pair out of the array because of that whitespace at the end of the pattern as you can see here...

Please don't propose other solutions with explode's and the implode's every other chunk. It has to be done with regex. TIA.

Upvotes: 0

Views: 103

Answers (1)

trincot
trincot

Reputation: 350137

You can use preg_match_all for this. So if your input string is $str, the $result can be achieved as follows:

$count = preg_match_all("~[^/]+/[^/]+~", $str, $result);

Upvotes: 1

Related Questions