How can I split a string in PHP at the nth occurrence of a needle?

It 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;
}

Personally I'd just split it into an array with explode, and then implode the first n-1 parts as the first half, and implode the remaining number as the second half.


Here's an approach that I would prefer over a regexp solution (see my other answer):

function split_nth($str, $delim, $n)
{
  return array_map(function($p) use ($delim) {
      return implode($delim, $p);
  }, array_chunk(explode($delim, $str), $n));
}

Just call it by:

split_nth("1 2 3 4 5 6", " ", 2);

Output:

array(3) {
  [0]=>
  string(3) "1 2"
  [1]=>
  string(3) "3 4"
  [2]=>
  string(3) "5 6"
}

If your needle will always be one character, use Galled's answer. It's going to be faster by quite a bit. If your $needle is a string, try this. It seems to work fine.

function splitn($string, $needle, $offset)
{
    $newString = $string;
    $totalPos = 0;
    $length = strlen($needle);
    for($i = 0; $i < $offset; $i++)
    {
        $pos = strpos($newString, $needle);

        // If you run out of string before you find all your needles
        if($pos === false)
            return false;
        $newString = substr($newString, $pos + $length);
        $totalPos += $pos + $length;
    }
    return array(substr($string, 0, $totalPos-$length), substr($string, $totalPos));
}

Tags:

Php

String