is there a way to use explode function to explode only by last delimiter occurrence?
$string = "one_two_ ... _three_four";
$explodeResultArray = e
$explodeResultArray = explode("_", $string);
$last_item = end($explodeResultArray);
$key = count($explodeResultArray) - 1;
unset($explodeResultArray[$key]);
$arr[] = (implode($explodeResultArray,'_'));
$arr[] = $last_item;
print_r($arr);
Output
Array
(
[0] => one_two_ ... _three
[1] => four
)
For such a taks, you can just use strstr and strrchr:
$valueBeforeLastUnderscore = rtrim(strrev(strstr(strrev($value), '_')), '_');
$valueAfterLastUnderscore = ltrim(strrchr($value, '_'), '_');
That being said, I like the regular expression answer more.
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
use end + explode
$explodeResultArray = end(explode("_", $string));
$explodeResultArray will = four
Use preg_match()
$string = "one_two_three_four";
$arr = array();
preg_match("/(^.*)_(.*?)$/", $string, $arr);
print_r($arr);
Output: Array ( [0] => one_two_three_four [1] => one_two_three [2] => four )
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