Quickest way to get the YouTube video id from a URL in PHP

I’ve written some custom plugins for WordPress which needed to extract the video id from a YouTube URL, so people could paste in any YouTube link in any format (short, long, whatever) and the code would still work. For this, I went through a lot of code snippets that perform various kinds of RegEx and parse_url calls and what not, but Istill thought that was too much work for something so trivial.

Then I thought… Since all YouTube video IDs are 11 characters anyway, why not just look for the only 11-character sequence in a YouTube URL string and extract that?

function quickYouTubeId($youtubeurl) {
    preg_match("#[a-zA-Z0-9-_]{11}#", $youtubeurl, $id);
    return (strlen($id[0])==11) ? $id[0] : false;

I can’t think of a YouTube URL that’ll foil this match. Can you?

Note: This function assumes that YouTube ids are 11-characters only – no more, no less. If we survive till a period of time when the ids get longer, i’ll update this function accordingly!

I’ve also put this piece of code up on GitHub. Download it, fork it, link back to it!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close