Alex
Alex

Reputation: 7688

Can't get preg_match to return the data needed

Ok so lets say I need to take a part this link: http://www.dailymotion.com/video/xnstwx_bmw-eco-pro-race_auto

I need to get

[0] => xnstwx

[1] => bmw-eco-pro-race_auto

and I am trying it with: preg_match('/video\/([A-Za-z0-9]+)_/i', $video['url'], $match);

and I get:

[0] => video/xnstwx_

[1] => xnstwx

than I try it with: preg_match('/video\/([A-Za-z0-9]+)_/([A-Za-z0-9-_]+)', $video['url'], $match); and I guess you already know that is wrong.

I have always ran away of regex for no reason and now I am trying to learn using a regular-expression cheat sheet but now I am a bit stuck :).

Upvotes: 1

Views: 225

Answers (4)

Philthi
Philthi

Reputation: 95

Use the following to get your matches in $match[1] and $match[2].

preg_match("/.*\/video\/([a-z0-9]+)_(.*)$/i", $video['url'], $match);

no need for A-Z with the i modifier, the first element in the array is always the fully matched expression, which is why the expected results are in position 1 and 2.

Regards, Phil,

EDIT: didn't realise I had to use code tags for the escaped slashes to show up!

Upvotes: 1

sanusart
sanusart

Reputation: 1527

A bit late, but:

<?php
$u = 'http://www.dailymotion.com/video/xnstwx_bmw-eco-pro-race_auto';
preg_match('/([A-Za-z0-9]+)_([A-Za-z0-9].+)/', $u,$m);
print_r($m);
?>

gives:

Array ( [0] => xnstwx_bmw-eco-pro-race_auto [1] => xnstwx [2] => bmw-eco-pro-race_auto ) 

Upvotes: 2

dorsh
dorsh

Reputation: 24740

preg_match('@video/([^_]+)_(.+)@', $video['url'], $match);

And a tip: it's always a good idea not to use / as the regex delimiter when dealing with urls, so you won't have to escape all the slashes in your pattern.

Upvotes: 1

Michael Berkowski
Michael Berkowski

Reputation: 270677

Add (.+) after the _. This traps one or more of any character, grouped by () following the _.

preg_match('/video\/([A-Za-z0-9]+)_(.+)/i', $video['url'], $match);

var_dump($match);
array(3) {
  [0]=>
  string(34) "video/xnstwx_bmw-eco-pro-race_auto"
  [1]=>
  string(6) "xnstwx"
  [2]=>
  string(21) "bmw-eco-pro-race_auto"
}

There are many potential ways to do this, but this is just the first example that came to mind.

Upvotes: 1

Related Questions