Alex Rivera | Logout

Youtube I.D parsing for new URL formats

Asked 2011-10-07T21:52:34.973
22

This question has been asked before and I found this:

Reg exp for youtube link

but I'm looking for something slightly different.

I need to match the Youtube I.D itself compatible with all the possible youtube link formats. Not exclusively beginning with youtube.com.

For example:

http://www.youtube.com/watch?v=-wtIMTCHWuI

http://www.youtube.com/v/-wtIMTCHWuI?version=3&autohide=1

http://youtu.be/-wtIMTCHWuI

http://www.youtube.com/oembed?url=http%3A//www.youtube.com/watch?v%3D-wtIMTCHWuI&format=json

http://s.ytimg.com/yt/favicon-wtIMTCHWuI.ico

http://i2.ytimg.com/vi/-wtIMTCHWuI/hqdefault.jpg

is there a clever strategy I can use to match the video I.D -wtIMTCHWuI compatible with all these formats. I'm thinking character counting and matching = ? / . & characters.

Edit
Report

1 Answer

0

Currently I'm using this:

function _getYoutubeVideoId($url)
{
  $parts = parse_url($url);

  //For seriously malformed urls
  if ($parts === false) {
     return false;
  }

  switch ($parts['host']) {
     case 'youtu.be':
        return substr($parts['path'], 1);
        break;
     case 'youtube.com':
     case 'www.youtube.com':
        parse_str($parts['query'], $params);
        return $params['v'];
        break;
     default:
        return false;
        break;
  } 
}

It could be extended, but right now it works for most of the cases

answered 2012-04-01T05:36:10.070

Your Answer