Skip to content

Instantly share code, notes, and snippets.

@ruturajpatki
Created June 11, 2024 05:23
Show Gist options
  • Select an option

  • Save ruturajpatki/5b842d99af445fc4f012a7f505aecfd5 to your computer and use it in GitHub Desktop.

Select an option

Save ruturajpatki/5b842d99af445fc4f012a7f505aecfd5 to your computer and use it in GitHub Desktop.
Simple PHP Function to extract YouTube Video ID from several different types of YouTube links.
function extractYouTubeID($url) {
$pattern = '%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)|embed/|v/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i';
preg_match($pattern, $url, $matches);
return $matches[1] ?? null;
}
/*
Here is a quick test of all supported YouTube URL types.
$urls = [
'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
'https://youtu.be/dQw4w9WgXcQ',
'https://www.youtube.com/embed/dQw4w9WgXcQ',
'https://www.youtube.com/v/dQw4w9WgXcQ?version=3&autohide=1',
'https://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtu.be',
'https://m.youtube.com/watch?v=dQw4w9WgXcQ',
'https://www.youtube.com/user/username#p/a/u/1/dQw4w9WgXcQ',
'https://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ'
];
echo '<pre>';
foreach ($urls as $url) {
echo 'URL: ' . $url . ' -> Video ID: ' . extractYouTubeID($url) . "\n";
}
echo '</pre>';
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment