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

后端 未结 12 1553
無奈伤痛
無奈伤痛 2020-11-29 08:25

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

12条回答
  •  心在旅途
    2020-11-29 08:48

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

提交回复
热议问题