Search code examples
phparrayssplitpreg-splitdelimited

Split a string AFTER every third instance of character


How can I explode a string at the position after every third semicolon (;)?

example data:

$string = 'piece1;piece2;piece3;piece4;piece5;piece6;piece7;piece8;';

Desired output:

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

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

$output[2] = 'piece7;piece8;'

Notice the trailing semicolons are retained.


Solution

  • 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;
    }