phparraysstringsplit

Create a 2-element array by exploding only on the last occurring delimiter


$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 first one. Can I specify somehow a right to left search?

Basically how do I explode from right to left. I want to pick up only the last instance of " - ".

Result I need:

$item[0] = 'this is my - string';
$item[1] = 'and more';

and not:

$item[0] = 'this is my';
$item[1] = 'string - and more';

Solution

  • You may use strrev to reverse the string, and then reverse the results back:

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

    Not sure if this is the best solution though.

    Actual output: (Demo)

    array (
      0 => 'and more',
      1 => 'string',
      2 => 'this is my',
    )