How to Explode String Right to Left?

前端 未结 12 802
灰色年华
灰色年华 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条回答
  •  Happy的楠姐
    2020-12-31 03:48

    Just an idea:

    function explode_reversed($delim,$s){
      $result = array();
      $w = "";
      $l = 0;
      for ($i = strlen($s)-1; $i>=0; $i-- ):
        if ( $s[$i] == "$delim" ):
          $l++;
          $w = "";
        else:
          $w = $s[$i].$w;
        endif;
        $result[$l] = $w;
      endfor;
    return $result;
    }
    $arr = explode_reversed(" ","Hello! My name is John.");
    print_r($arr);
    

    Result:

    Array
    (
        [0] => John.
        [1] => is
        [2] => name
        [3] => My
        [4] => Hello!
    )
    

    But this is much slower then explode. A test made:

    $start_time = microtime(true);
    for ($i=0; $i<1000;$i++)   
      $arr = explode_reversed(" ","Hello! My name is John.");
    $time_elapsed_secs = microtime(true) - $start_time;
    echo "time: $time_elapsed_secs s
    ";

    Takes 0.0625 - 0.078125s

    But

    for ($i=0; $i<1000;$i++)   
      $arr = explode(" ","Hello! My name is John.");
    

    Takes just 0.015625s

    The fastest solution seems to be:

    array_reverse(explode($your_delimiter, $your_string));
    

    In a loop of 1000 times this is the best time I can get 0.03125s.

提交回复
热议问题