0

First of all, I want to say that I know there are a bunch of related questions, but after trying the solutions given in these topics, I still have something that doesn't work for my code..

I need a regex for extracting the youtube vid from this specific type of Url:

http://www.youtube.com/user/thedailyenglishshow#p/u/0/B3-Bn4aUXTY

My php code and patterns used look like this:

public function retrieveUserVideo($data) {

  $url = $data;
  $pattern = '/[^\/]+$/';
  //$pattern = '(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+';
  preg_match($pattern, $url, $matches);
  $result = $matches[1];

  return $result;
 }

I have checked these patterns at 'http://gskinner.com/RegExr/', and they seem to work, but i receive an empty result string with the first pattern, while with the second one i get an unknown modifier '[' error. If i put the pattern between '#' i get the empty string result.

Any ideas of what's wrong with the code shown? Please help me, im really desperate!

John Parker
  • 54,048
  • 11
  • 129
  • 129
Iker
  • 3
  • 1
  • The problem was you are not capturing anything "( )" with your regex. Steven's answer should work – brian_d Jan 17 '11 at 18:15
  • The answer to this question might help you... http://stackoverflow.com/questions/2936467/parse-youtube-video-id-using-preg-match/6382259#6382259 – Benjam Oct 12 '11 at 05:45

2 Answers2

1

You're going to need PHP regex delimiters around your pattern, so that might have caused your errors. But what are your parsing requirements to begin with? If you just watch to fetch the video ID, why not just capture all characters after the final slash? /\/([^\/]*)$/ will return B3-Bn4aUXTY for $matches[1] in your example.

Steven
  • 17,796
  • 13
  • 66
  • 118
  • I needed to parse the whole url for security purposes, but given that your pattern works fine, i will make sure it is only a youtube url before i pass the data to this function. Really simple solution thank you very much for the help! – Iker Jan 17 '11 at 18:20
  • What security purposes are you talking about? If all you need to do is get the video id and you can determine the set of all characters that can show up in the id, you can just refine your match to `/\/([-A-Za-z0-9]*)$/`. Sure you'll get some false positives, but you won't expose yourself to unsafe data. – Steven Jan 17 '11 at 18:41
1

What about a simple explode to get the last part?

public function retrieveUserVideo($data) {
    $parts = explode('/', $data);
    return end($parts);
}
scoffey
  • 4,638
  • 1
  • 23
  • 27