Last active
August 11, 2023 23:00
-
-
Save jmillerdesign/1553772 to your computer and use it in GitHub Desktop.
Get YouTube video 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 | |
/* | |
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
commented
Aug 11, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment