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

后端 未结 12 1560
無奈伤痛
無奈伤痛 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:59

    function split_nth($haystack, $needle, $nth){
        $result = array();
        if(substr_count($haystack,$needle) > ($nth-1)){
            $haystack = explode($needle, $haystack);
            $result[] = implode(array_splice($haystack, 0, $nth), $needle);
            $result[] = implode($haystack, $needle);
        }
        return $result;
    }
    

提交回复
热议问题