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

后端 未结 12 1540
無奈伤痛
無奈伤痛 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 09:07

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

提交回复
热议问题