Dɑvïd Dɑvïd - 1 year ago 83
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

, and want to split it at nth occurrence of
, and in my case,
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;
$arr[] = substr($string,0,$i);
$arr[] = substr($string,$i+1,$max);

return $arr;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download