Anish
Anish

Reputation: 5078

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';

Upvotes: 1

Views: 143

Answers (3)

Anatoliy  Gusarov
Anatoliy Gusarov

Reputation: 808

This one is simplest one

$result = preg_split('%_(?=(\d|http://))%si', $subject);

Upvotes: 1

HamZa
HamZa

Reputation: 14931

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

Upvotes: 3

Atber
Atber

Reputation: 465

Use

preg_match('/(\d)_(\d)_(\d)_([\w:\.\/\/\-]+)_([\d]{2}:[\d]{2}:[\d]{2})/', $link, $matches);

And $matches:

array(6) {
  [0]=>
  string(95) "7_5_7_http://test.com/folder/images/7_newim/5_car/7_february2013/p/a00/p01/video-1.mov_00:00:09"
  [1]=>
  string(1) "7"
  [2]=>
  string(1) "5"
  [3]=>
  string(1) "7"
  [4]=>
  string(80) "http://test.com/folder/images/7_newim/5_car/7_february2013/p/a00/p01/video-1.mov"
  [5]=>
  string(8) "00:00:09"
}

Upvotes: 2

Related Questions