1

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';
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Anish
  • 4,262
  • 6
  • 36
  • 58
  • 1
    Take a look at [preg_match](http://php.net/manual/en/function.preg-match.php) and http://www.regular-expressions.info/ to get started. – elclanrs May 28 '13 at 05:12
  • For a task that involves strings with unknown string variability, we cannot recommend a "best" solution by only knowing one sample string. There are too many ways that this task can be achieved "correctly", but many of these solutions may only be suitable for the single presented string. Needs More Clarity. – mickmackusa Sep 02 '22 at 21:01

3 Answers3

3

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

HamZa
  • 14,671
  • 11
  • 54
  • 75
2

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"
}
Atber
  • 465
  • 2
  • 5
1

This one is simplest one

$result = preg_split('%_(?=(\d|http://))%si', $subject);
Anatoliy Gusarov
  • 797
  • 9
  • 22
  • The `s` pattern modifier is useless here because there are no dots in the pattern. This answer is missing its educational explanation. – mickmackusa Sep 02 '22 at 20:55