$split_point = ' - ';
$string = 'this is my - string - and more';
How can I make a split using the second instance of $split_point
and not the first one. Can I specify somehow a right to left search?
Basically how do I explode from right to left. I want to pick up only the last instance of " - ".
Result I need:
$item[0]='this is my - string';
$item[1]='and more';
and not:
$item[0]='this is my';
$item[1]='string - and more';
Use the str. rsplit() method with maxsplit set to 1 to split a string and get the last element. The rsplit() method splits from the right and will only perform a single split when maxsplit is set to 1 .
Python provides a method that split the string from rear end of the string. The inbuilt Python function rsplit() that split the string on the last occurrence of the delimiter. In rsplit() function 1 is passed with the argument so it breaks the string only taking one delimiter from last.
Both are used to split a string into an array, but the difference is that split() uses pattern for splitting whereas explode() uses string. explode() is faster than split() because it doesn't match string based on regular expression.
You may use strrev to reverse the string, and then reverse the results back:
$split_point = ' - ';
$string = 'this is my - string - and more';
$result = array_map('strrev', explode($split_point, strrev($string)));
Not sure if this is the best solution though.
How about this:
$parts = explode($split_point, $string);
$last = array_pop($parts);
$item = array(implode($split_point, $parts), $last);
Not going to win any golf awards, but it shows intent and works well, I think.
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