Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to explode only on the last occurring delimiter?

$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';
like image 380
Codex73 Avatar asked Apr 04 '09 16:04

Codex73


People also ask

How do you split a string at the last delimiter in Python?

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 .

How do you split the last instance of a character in python?

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.

What is the difference between explode () Y split ()?

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.


2 Answers

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.

like image 102
moff Avatar answered Sep 24 '22 13:09

moff


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.

like image 21
Paolo Bergantino Avatar answered Sep 22 '22 13:09

Paolo Bergantino