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?
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.
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.
Examples ¶ $str = "Hello Friend"; $arr1 = str_split($str); $arr2 = str_split($str, 3); print_r($arr1);
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With