Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 in the strpos comments in the PHP manual, but that seems a bit much for what I need.

I have plain text as $string and want to split it at nth occurrence of $needle, and in my case, needle is simply a space. (I can do the sanity checks!)

How can I do it?

like image 405
Dɑvïd Avatar asked May 10 '11 20:05

Dɑvïd


People also ask

How do you split a string in PHP?

PHP | explode() Function explode() is a built in function in PHP used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs.

How do you find the nth occurrence of a character in a string?

1) Select Lookup from the drop-down list of Formula Type section; 2) Choose Find where the character appear Nth in a string in Choose a formula section; 3) Select the cell which contains the string you use, then type the specified character and nth occurrence in to the textboxes in the Arguments input section.

How can I get half string in PHP?

Examples ¶ $str = "Hello Friend"; $arr1 = str_split($str); $arr2 = str_split($str, 3); print_r($arr1);

What is split function in PHP?

Definition and Usage. The split() function will divide a string into various elements, the boundaries of each element based on the occurrence of pattern in string.


1 Answers

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; } 
like image 159
Galled Avatar answered Nov 02 '22 03:11

Galled