Last active
July 5, 2021 15:37
-
-
Save leogopal/b429f9700d473a55f70819dc6e5195f0 to your computer and use it in GitHub Desktop.
PHP function to get youtube ID from URL
This file contains 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 | |
function get_youtube_video_ID($youtube_video_url) { | |
/** | |
* Pattern matches | |
* http://youtu.be/ID | |
* http://www.youtube.com/embed/ID | |
* http://www.youtube.com/watch?v=ID | |
* http://www.youtube.com/?v=ID | |
* http://www.youtube.com/v/ID | |
* http://www.youtube.com/e/ID | |
* http://www.youtube.com/user/username#p/u/11/ID | |
* http://www.youtube.com/leogopal#p/c/playlistID/0/ID | |
* http://www.youtube.com/watch?feature=player_embedded&v=ID | |
* http://www.youtube.com/?feature=player_embedded&v=ID | |
*/ | |
$pattern = | |
'% | |
(?:youtube # Match any youtube url www or no www , https or no https | |
(?:-nocookie)?\.com/ # allows for the nocookie version too. | |
(?:[^/]+/.+/ # Once we have that, find the slashes | |
|(?:v|e(?:mbed)?)/|.*[?&]v=) # Check if its a video or if embed | |
|youtu\.be/) # Allow short URLs | |
([^"&?/ ]{11}) # Once its found check that its 11 chars. | |
%i'; | |
// Checks if it matches a pattern and returns the value | |
if (preg_match($pattern, $youtube_video_url, $match)) { | |
return $match[1]; | |
} | |
// if no match return false. | |
return false; | |
} | |
?> |
Confirmed, does not get watch?v=
The pattern itself works, it just won't work with those comments in the way. Maybe the carriage returns as well, I haven't checked.
But yeah, if you change it to a single line like:
$pattern = '%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i';
then it works, at least with ?v=ID
.
The pattern itself works, it just won't work with those comments in the way. Maybe the carriage returns as well, I haven't checked.
But yeah, if you change it to a single line like:
$pattern = '%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i';
then it works, at least with?v=ID
.
Confirmed, this works
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://www.youtube.com/watch?v=ID
doesn't return ID