Dɑvïd Dɑvïd - 2 months ago 17
PHP Question

How to split a string in PHP at nth occurrence of needle?

There must be a fast and efficient way to split a (text) string at the "nth" occurrence of a needle, but I cannot find it. There is a fairly full set of functions in the strpos comments in the PHP manual, but that seems a bit much for what I need.

I have plain text as

$string
, and want to split it at nth occurrence of
$needle
, and in my case,
needle
is simply a space. (I can do the sanity checks!)

Can someone point me in the right direction? Many thanks!

Answer Source

Could be?

function split2($string,$needle,$nth){
$max = strlen($string);
$n = 0;
for($i=0;$i<$max;$i++){
    if($string[$i]==$needle){
        $n++;
        if($n>=$nth){
            break;
        }
    }
}
$arr[] = substr($string,0,$i);
$arr[] = substr($string,$i+1,$max);

return $arr;
}