Explode only by last delimiter

后端 未结 11 1670
隐瞒了意图╮
隐瞒了意图╮ 2021-01-03 17:30

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

$string = "one_two_  ... _three_four";

$explodeResultArray = e         


        
相关标签:
11条回答
  • 2021-01-03 18:02
    $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
    )
    
    0 讨论(0)
  • 2021-01-03 18:03

    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.

    0 讨论(0)
  • 2021-01-03 18:05

    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
    
    0 讨论(0)
  • 2021-01-03 18:06

    use end + explode

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

    $explodeResultArray will = four

    0 讨论(0)
  • 2021-01-03 18:13

    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 )

    0 讨论(0)
  • 2021-01-03 18:16

    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

    0 讨论(0)
提交回复
热议问题