0

My site uses javascript which reads youtube video ID's from an array. In the format:

1:  'A8JsRx2loix',
2:  'XFGAQrEUaes',
3:  'qX9FSZJu44s'

Whats the best way to take a list of urls like

http://www.youtube.com/watch?feature=player_detailpage&v=bCJ-qARb2M0
http://www.youtube.com/watch?feature=player_detailpage&v=bCJ-qAswdM2
http://www.youtube.com/watch?feature=player_detailpage&v=bCJ-sh7b2M0

and extract the 11 digit video ids, putting them in the given format above.

NOTE: the urls can be in different formats, for example when they are in playlists.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
user2228313
  • 119
  • 1
  • 3
  • 11
  • 3
    You can use `parse_url($url)` and extract `v=VIDEO ID` – u54r Apr 16 '13 at 00:43
  • Yes it starts with finding the 'v=' and the following ampersand then cutting off the left and right side. You'll need a regular expression for cleanliness because how can you be sure the 'v=' will end up where you are showing us above? If you are sure then you can do a find and left/right trim and keep just the ID....I'll see if I can whip you something up (unless someone beats me to it). – Frank Tudor Apr 16 '13 at 00:55

1 Answers1

1

You can use this function which should deal with any youtube url, It will return an object like:

{
    type: 'youtube',
    id: 'A8JsRx2loix'
}

function testUrlForMedia(url) {
    var success = false;
    var media = {};
    if (url.match('http://(www.)?youtube|youtu\.be')) {
        if (url.match('embed')) {
            youtube_id = url.split(/embed\//)[1].split('"')[0];
        }
        else {
            youtube_id = url.split(/v\/|v=|youtu\.be\//)[1].split(/[?&]/)[0];
        }
        media.type = "youtube";
        media.id = youtube_id;
        success = true;
    }
    if (success) {
        return media;
    }
    return false;
}

Original Source

Community
  • 1
  • 1
Hailwood
  • 89,623
  • 107
  • 270
  • 423