Get Youtube Video ID from html code with PHP

There are generally two formats for YouTube video urls:

http://www.youtube.com/v/[videoid]
http://www.youtube.com/watch?v=[videoid]

The “www.youtube.com” can be replaced by “www.youtube.co.uk”, or other country codes, but as far as I’ve been able to determine, the video ids are the same regardless of the domain name.

The video id is an 11-character string that uses base-64 encoding.

Assuming you have code that will parse urls from an HTML document, you can determine if it’s a YouTube video url and get the video id by using this regex (written in C#, but should be easily converted to php or anything else):

"^http://(?<domain>([^./]+\\.)*youtube\\.com)(/v/|/watch\\?v=)(?<videoId>[A-Za-z0-9_-]{11})"

This particular regex is specific to youtube.com. Making it understand all the different country codes (youtube.co.uk, youtube.pl, youtube.it, etc.) is somewhat more involved.

Leave a Comment