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

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

    I've edited Galled's function to make it explode after every nth occurrences instead of just the first one.

    function split2($string, $needle, $nth) {
      $max = strlen($string);
      $n = 0;
      $arr = array();
    
      //Loop trough each character
      for ($i = 0; $i < $max; $i++) {
    
        //if character == needle
        if ($string[$i] == $needle) {
          $n++;
          //Make a string for every n-th needle
          if ($n == $nth) {
            $arr[] = substr($string, $i-$nth, $i);
            $n=0; //reset n for next $nth
          }
          //Include last part of the string
          if(($i+$nth) >= $max) {
            $arr[] = substr($string, $i + 1, $max);
            break;
          }
        }
      }
      return $arr;
    }
    

提交回复
热议问题