Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explode only by last delimiter

Tags:

php

is there a way to use explode function to explode only by last delimiter occurrence?

$string = "one_two_  ... _three_four";

$explodeResultArray = explode("_", $string);

Result Should Be:

echo $explodeResultArray[0]; // "one_two_three ...";
echo $explodeResultArray[1]; // "four";
like image 640
Farid Movsumov Avatar asked May 17 '13 13:05

Farid Movsumov


People also ask

How do you split a string at the last delimiter 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.

How do you split the last element 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 .

What is the difference between explode () and split () functions?

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.

What does the explode () function do?

The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string.


Video Answer


3 Answers

Straightforward:

$parts = explode('_', $string);
$last = array_pop($parts);
$parts = array(implode('_', $parts), $last);
echo $parts[0]; // outputs "one_two_three"

Regular expressions:

$parts = preg_split('~_(?=[^_]*$)~', $string);
echo $parts[0]; // outputs "one_two_three"

String reverse:

$reversedParts = explode('_', strrev($string), 2);
echo strrev($reversedParts[0]); // outputs "four"
like image 100
soulmerge Avatar answered Nov 05 '22 20:11

soulmerge


There is no need for a workaround. explode() accepts a negative limit.

$string = "one_two_three_four";
$part   = implode('_', explode('_', $string, -1));
echo $part;

Result is

one_two_three
like image 41
nibra Avatar answered Nov 05 '22 20:11

nibra


I chose to use substring becasue you want a string up to a particular point:

$string = "one_two_three_four_five_six_seven";
$part1 = substr("$string",0, strrpos($string,'_'));
$part2 = substr("$string", (strrpos($string,'_') + 1));
var_dump($part1,$part2);

RESULTS:

string(27) "one_two_three_four_five_six"
string(5) "seven"
like image 20
Useless Intern Avatar answered Nov 05 '22 21:11

Useless Intern