Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to parse youtube yid

Tags:

regex

php

youtube

Example URLs

http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo
http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel
http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub
http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I

Any regex that will pull the correct YID from all 4 of these use cases? The first case is especially odd.

Thank you.

like image 270
putorti Avatar asked Apr 08 '10 01:04

putorti


2 Answers

(?<=v=)[a-zA-Z0-9-_]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+

This works. http://i.imgur.com/SQJW2.jpg

like image 66
webnat0 Avatar answered Oct 26 '22 22:10

webnat0


For what it's worth, this worked on http://rubular.com/

(v=|\/)([\w-]+)(&.+)?$

Grabbing second capture group for these:

http://www.youtube.com/user/SilkRoadTheatre#p/a/u/2/6dwqZw0j_jY
http://youtu.be/6dwqZw0j_jY
http://www.youtube.com/watch?v=6dwqZw0j_jY&feature=youtu.be
http://youtu.be/afa-5HQHiAs
http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo
http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel
http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub
http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I

(the editor made me tab the URLs in as code, sorry)

like image 33
Joe Sak Avatar answered Oct 26 '22 23:10

Joe Sak