Explode only by last delimiter

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"

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

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"

You could do the following:

$string = "one_two_three_four";
$explode = explode('_', $string); // split all parts

$end = '';
$begin = '';

if(count($explode) > 0){
    $end = array_pop($explode); // removes the last element, and returns it

    if(count($explode) > 0){
        $begin = implode('_', $explode); // glue the remaining pieces back together
    }
}

EDIT: array_shift should have been array_pop

Tags:

Php