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

后端 未结 12 1536
無奈伤痛
無奈伤痛 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条回答
  •  萌比男神i
    2020-11-29 09:03

    Taking Matthew's answer and adding a solution for Dɑvïd's comment:

    function split_nth($str, $delim, $n) {
      $result = array_map(function($p) use ($delim) {
          return implode($delim, $p);
      }, array_chunk(explode($delim, $str), $n));
      $result_before_split = array_shift($result);
      $result_after_split = implode(" ", $result); 
      return array($result_before_split, $result_after_split);
    }
    

    Just call it by:

    list($split_before, $split_after) = split_nth("1 2 3 4 5 6", " ", 2);
    

    Output:

    1 2
    3 4 5 6
    

提交回复
热议问题