Created
June 11, 2024 05:23
-
-
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.
This file contains hidden or 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
| 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