Skip to content

Instantly share code, notes, and snippets.

@aalaap
Last active February 5, 2019 10:55
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aalaap/3187024 to your computer and use it in GitHub Desktop.
Save aalaap/3187024 to your computer and use it in GitHub Desktop.
Easy little function to get the video ID from any YouTube URL.
<php
/**
* quickYouTubeId: Easy little function to get the video ID from any YouTube
* URL.
*
* I went through a lot of snippets that perform various kinds of RegEx and
* parse_url and what not, but I thought, since most YouTube video IDs are 11
* characters, why not just look for the only 11-character string and extract
* that? I can't think of a YouTube URL that'll foil this match. Can you?
*
* 2018-06-06 - fixed the problem with other non-video IDs in the URL
* 2016-12-28 - modernized and made it more PSR-2 compliant and shorter
* 2012-07-28 - fixed for underscore matching
* 2012-07-27 - first release
*
* @param String $youTubeUrl The URL of the video in any format supported
* by YouTube
* @return String The 11-character YouTube video ID.
* @author Aalaap Ghag <aalaap@gmail.com>
*/
function quickYouTubeId($youTubeUrl) {
return preg_match
"/(?:[\/]|v=)([a-zA-Z0-9-_]{11})/",
$youTubeUrl,
$id)
? $id[1]
: false;
}
@aalaap
Copy link
Author

aalaap commented Jul 6, 2018

@itzmukeshy7 Slightly tricky, due to the various formats. Maybe I could make it check for v=fRh_vgS2dFE or /fRh_vgS2dFE?

Edit: Fixed it! Thanks for reporting!

@rossor10
Copy link

You left out a "(" after preg_match.

@aalaap
Copy link
Author

aalaap commented Feb 5, 2019

If anyone's still looking for this, it's now available as a provider for the excellent Faker library: https://github.com/aalaap/faker-youtube

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment