Last active
February 5, 2019 10:55
-
-
Save aalaap/3187024 to your computer and use it in GitHub Desktop.
Easy little function to get the video ID from any YouTube URL.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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 <[email protected]> | |
*/ | |
function quickYouTubeId($youTubeUrl) { | |
return preg_match | |
"/(?:[\/]|v=)([a-zA-Z0-9-_]{11})/", | |
$youTubeUrl, | |
$id) | |
? $id[1] | |
: false; | |
} |
Awesome. After many searches and experiments, this is not only the simplest solution I found, but the only one that worked!
It doesn't work if the first query value is not video id like this:
https://www.youtube.com/watch?list=RDfRh_vgS2dFE&v=fRh_vgS2dFE
Works for :
https://www.youtube.com/watch?v=fRh_vgS2dFE&list=RDfRh_vgS2dFE
Can we do anything?
@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!
You left out a "(" after preg_match.
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
The original function didn't match underscores. D'oh! Fixed.