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

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

    This is ugly, but it seems to work:

    $foo = '1 2 3 4 5 6 7 8 9 10 11 12 13 14';
    
    $parts = preg_split('!([^ ]* [^ ]* [^ ]*) !', $foo, -1,
                PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
    
    var_dump($parts);
    

    Output:

    array(5) {
      [0]=>
      string(5) "1 2 3"
      [1]=>
      string(5) "4 5 6"
      [2]=>
      string(5) "7 8 9"
      [3]=>
      string(8) "10 11 12"
      [4]=>
      string(5) "13 14"
    }
    

    Replace the single spaces in the query with a single character you wish to split on. This expression won't work as-is with multiple characters as the delimiter.

    This is hard coded for every third space. With a little tweaking, probably could be easily adjusted. Although a str_repeat to build a dynamic expression would work as well.

提交回复
热议问题