There are several ways to accomplish your task.
# 1: preg_split()
( ) ( )
function p_explode($delim,$string,$max_elements){
return preg_split('/(?:[^'.$delim.']+\K'.$delim.'){'.$max_elements.'}/',$string);
}
# 2: ( )
function p_explode($delim,$string,$max_elements){
return array_map(
function($v)use($delim){
return implode($delim,$v);
},
array_chunk(explode($delim,$string),$max_elements)
);
}
№ 3: ( )
function p_explode($delim,$string,$max_elements){
$delim_len=strlen($delim);
$pos=-1; // set $pos
$i=1; // set $i
while(false!==$pos=strpos($string,$delim,$pos+1)){ // advance $pos while $delim exists
if($i<$max_elements){
++$i; // increment ($max_elements-1) times
}else{
$result[]=substr($string,0,$pos); // on ($max_elements)th time, store substring
$string=substr($string,$pos+$delim_len); // update $string with what is leftover(after delimiter)
$pos=-1; // reset $pos
$i=1; // reset $i
}
}
if($i){
$result[]=$string; // if anything left, store as final element
}
return $result;
}
. (PHP Demo)
Input:
$strings=[
'1,2,3,4,5,6,7',
'1,2,3,4,5,6,7,8',
'1,2,3,4,5,6,7,8,9,10',
'1,2,3,4,5,6,7,8,9,10,11,12,13',
'1,2,3,4,5,6,7,8,9,10,11,12,13,14,15',
'1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18'
];
:
foreach($strings as $string){
var_export(p_explode(',',$string,8));
echo "\n\n";
}
:
array (
0 => '1,2,3,4,5,6,7',
)
array (
0 => '1,2,3,4,5,6,7,8',
)
array (
0 => '1,2,3,4,5,6,7,8',
1 => '9,10',
)
array (
0 => '1,2,3,4,5,6,7,8',
1 => '9,10,11,12,13',
)
array (
0 => '1,2,3,4,5,6,7,8',
1 => '9,10,11,12,13,14,15',
)
array (
0 => '1,2,3,4,5,6,7,8',
1 => '9,10,11,12,13,14,15,16',
2 => '17,18',
)
* . regex , (preg_quote() ).