Created
September 30, 2011 20:28
-
-
Save afeld/1254889 to your computer and use it in GitHub Desktop.
YouTube video ID regex
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
# Parses YouTube URLs directly or from iframe code. Handles: | |
# * Address bar on YouTube url (ex: http://www.youtube.com/watch?v=ZFqlHhCNBOI) | |
# * Direct http://youtu.be/ url (ex: http://youtu.be/ZFqlHhCNBOI) | |
# * Full iframe embed code (ex: <iframe src="http://www.youtube.com/embed/ZFqlHhCNBOI">) | |
# * Old <object> tag embed code (ex: <object><param name="movie" value="http://www.youtube.com/v/ZFqlHhCNBOI">...) | |
/(youtu\.be\/|youtube\.com\/(watch\?(.*&)?v=|(embed|v)\/))([^\?&"'>]+)/ | |
$5 #=> the video ID | |
# test it on Rubular: http://rubular.com/r/eaJeSMkJvo |
Same thing for php - must remove trailing \W
. I also had to enclose it in slashes /
.
Thanks, I use it in PHP:
function getYoutubeId($url)
{
// original regex source: https://gist.github.com/afeld/1254889#gistcomment-1253992
$regex = '/(?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/mi';
preg_match($regex, $url, $matches);
return isset($matches[1]) ? $matches[1] : null;
}
$url = 'https://www.youtube.com/watch?v=SN102svZHQg';
echo getYoutubeId($url); // SN102svZHQg
private const MAGIC_REGEX = '#^(?:https?://|//)?(?:www\.|m\.|.+\.)?(?:youtu\.be/|youtube\.com/(?:embed/|v/|shorts/|feeds/api/videos/|watch\?v=|watch\?.+&v=))([\w-]{11})(?![\w-])#';
added support for shorts :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@toots it works for me removing the last
\W