How to Explode String Right to Left?

前端 未结 12 714
灰色年华
灰色年华 2020-12-31 03:22
$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

相关标签:
12条回答
  • 2020-12-31 03:38

    I've stumbled uppon the same, and fixed it like so:

    $split_point = ' - ';
    $string = 'this is my - string - and more';
    
    $reverse_explode = array_reverse(explode($split_point, $string));
    
    0 讨论(0)
  • 2020-12-31 03:38

    this is my - string - and more

    1. Use common explode function to get all strings
    2. Get sizeof array and fetch last item
    3. Pop last item using array_pop function.
    4. Implode remaining string with same delimeter(if u want other delimeter can use).

    Code

    $arrSpits=explode("", "this is my - string - and more");
    $arrSize=count($arrSpits);
    
    echo "Last string".$arrSpits[arrSize-1];//Output: and more
    
    
    array_pop(arrSpits); //now pop the last element from array
    
    $firstString=implode("-", arrSpits);
    echo "First String".firstString; //Output: this is my - string
    
    0 讨论(0)
  • 2020-12-31 03:43

    Why not split on ' - ', but then join the first two array entries that you get back together?

    0 讨论(0)
  • 2020-12-31 03:46

    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.

    0 讨论(0)
  • 2020-12-31 03:47

    I liked Moff's answer, but I improved it by limiting the number of elements to 2 and re-reversing the array:

    $split_point = ' - ';
    $string = 'this is my - string - and more';
    
    $result = array_reverse(array_map('strrev', explode($split_point, strrev($string),2)));
    

    Then $result will be :

    Array ( [0] => this is my - string [1] => and more )
    
    0 讨论(0)
  • 2020-12-31 03:47

    Not sure why no one posted a working function with $limit support though here it is for those who know that they'll be using this frequently:

    <?php
    function explode_right($boundary, $string, $limit)
    {
     return array_reverse(array_map('strrev', explode(strrev($boundary), strrev($string), $limit)));
    }
    
    $string = 'apple1orange1banana1cupuacu1cherimoya1mangosteen1durian';
    echo $string.'<br /><pre>'.print_r(explode_right(1, $string, 3),1).'</pre>';
    ?>
    
    0 讨论(0)
提交回复
热议问题