Search code examples
phpstringsplit

Split string into 2 strings after encountering the Nth vaue of a comma-delimited string


So, I have a comma delimited string which I want to split into two strings after count of x commas.

So, if my string was as follows:

temp1, temp2, temp3, temp4, temp5, temp6, temp7, temp8, temp9, temp10

I want to split it into two strings after a count of 4 commas, I would expect:

$string1 = 'temp1, temp2, temp3, temp4, ';

$string2 = 'temp5, temp6, temp7, temp8, temp9, temp10';

How can I achieve this in PHP?


Solution

  • There are lots of ways to do this - one approach would be to explode the string and then implode slices of that array like this:

    $x = 4;
    $delim = ', ';
    $str = 'temp1, temp2, temp3, temp4, temp5, temp6, temp7, temp8, temp9, temp10';
    $parts = explode($delim,$str);
    $string1 = implode($delim,array_slice($parts,0,$x)) . $delim;
    $string2 = implode($delim,array_slice($parts,$x));
    

    To me, this is the cleanest and most readable way to get the job done and does not require a loop.