Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php explode every third instance of character

Tags:

php

How can I explode every third semicolon (;) as a piece?

example data: $string = piece1;piece2;piece3;piece4;piece5;piece6;piece7;piece8;

example output would be:

$output[0] = piece1;piece2:piece3;

$output[1] = piece4;piece5;piece6;

$output[2] = piece7;piece8;

Thanks!

like image 472
stunnaman Avatar asked Aug 13 '09 22:08

stunnaman


1 Answers

I am sure you can do something slick with regular expressions, but why not just explode the each semicolor and then add them three at a time.

$tmp = explode(";", $string);
$i=0;
$j=0;

foreach($tmp as $piece) {
   if(! ($i++ %3)) $j++;   //increment every 3 
   $result[$j] .= $piece;
}
like image 151
jW. Avatar answered Sep 28 '22 19:09

jW.