TheoG TheoG - 4 months ago 29
PHP Question

PHP: Split string into 2 strings based on a comma delimited count of X

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?

Answer

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.