Skip to content

Instantly share code, notes, and snippets.

@jmillerdesign
Last active August 11, 2023 23:00
Show Gist options
  • Save jmillerdesign/1553772 to your computer and use it in GitHub Desktop.
Save jmillerdesign/1553772 to your computer and use it in GitHub Desktop.
Get YouTube video ID from URL
<?php
/*
Works for the following inputs and more:
dQw4w9WgXcQ
http://www.youtube.com/?v=dQw4w9WgXcQ
http://www.youtube.com/embed/dQw4w9WgXcQ
http://www.youtube.com/username#p/c/5555550123/0/dQw4w9WgXcQ
http://www.youtube.com/v/dQw4w9WgXcQ
http://www.youtube.com/v/dQw4w9WgXcQ?feature=autoshare&version=3&autohide=1&autoplay=1
http://www.youtube.com/watch?v=dQw4w9WgXcQ&hd=1&t=26s
http://www.youtube.com/watch?v=dQw4w9WgXcQ
http://youtu.be/dQw4w9WgXcQ
http://youtu.be/dQw4w9WgXcQ?hd=1&t=7s
<iframe width="560" height="315" src="http://www.youtube.com/embed/dQw4w9WgXcQ" frameborder="0" allowfullscreen></iframe>
*/
/**
* Get 11-character YouTube video ID from a URL
*
* @param string $url URL to video
* @return string 11 character string on success, empty string on failure
*/
function getYouTubeId($url) {
// Make sure you've entered a valid URL
if (!is_string($url) || (strlen($url) < 11)) {
return '';
}
// Get the 11-character ID from the URL
if (strlen($url) == 11) {
// Code was entered directly
$code = $url;
} else if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match)) {
$code = $match[1];
} else {
$code = '';
}
// Make sure code is correct
$code = preg_replace('/[^0-9a-zA-Z-_]/', '', $code);
if (strlen($code) != 11) {
$code = '';
}
return $code;
}
@Asdcg
Copy link

Asdcg commented Aug 11, 2023

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