Search code examples
phpregexsplittext-parsingdelimited

Split an underscore-delimited string, but ignore underscores occurring in a url


Below string I need to split. I tried with the explode(), but it is fragmenting the url substring.

$link = "7_5_7_http://test.com/folder/images/7_newim/5_car/7_february2013/p/a00/p01/video-1.mov_00:00:09";

$ex_link = explode('_',$link);

It is splitting the string after every "_' symbol, but I need to the results like this:

$ex_link[0] = '7';
$ex_link[1] = '5';
$ex_link[2] = '7';
$ex_link[3] = 'http://test.com/folder/images/7_newim/5_car/7_february2013/p/a00/p01/video-1.mov';
$ex_link[2] = '00:00:09';

Solution

  • Explode has a third parameter, why do people complicate things ?

    $link = "7_5_7_http://test.com/folder/images/7_newim/5_car/7_february2013/p/a00/p01/video-1.mov_00:00:09";
    $array = explode('_', $link, 4);
    $temp = array_pop($array);
    $array = array_merge($array, array_reverse(array_map('strrev', explode('_', strrev($temp), 2)))); // Now it has just become complexer (facepalm)
    print_r($array);
    

    Output:

    Array
    (
        [0] => 7
        [1] => 5
        [2] => 7
        [3] => http://test.com/folder/images/7_newim/5_car/7_february2013/p/a00/p01/video-1.mov
        [4] => 00:00:09
    )
    

    Online demo