Created
May 19, 2024 21:53
-
-
Save Oleksandr-Moik/83584552f9f94db952cdd75bf9eece39 to your computer and use it in GitHub Desktop.
Extract the YouTube Video ID from a URL in PHP (Larave, test suite on Pest)
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 | |
if (!function_exists('get_youtube_video_id')) { | |
function get_youtube_video_id(?string $url): ?string | |
{ | |
if (empty($url)) { | |
return null; | |
} | |
$pattern = | |
'%^# Match any youtube URL | |
(?:https?://)? # Optional scheme. Either http or https | |
(?:www\.)? # Optional www subdomain | |
(?: # Group host alternatives | |
youtu\.be/ # Either youtu.be, | |
| youtube\.com # or youtube.com | |
(?: # Group path alternatives | |
/embed/ # Either /embed/ | |
| /v/ # or /v/ | |
| /shorts/ # or /shorts/ | |
| /watch\?.*?v= # or /watch\?v= followed by any characters (non-greedy) | |
) # End path alternatives. | |
) # End host alternatives. | |
([\w-]+) # Allow any number of characters for YouTube ID. | |
(?:&?.*)? # Optional parameters after YouTube ID. | |
$%x'; | |
$result = preg_match($pattern, $url, $matches); | |
if ($result) { | |
return $matches[1]; | |
} | |
return null; | |
} | |
} |
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 | |
it('extracts video ID from YouTube URLs', function ($url, $expectedId) { | |
expect(get_youtube_video_id($url))->toBe($expectedId); | |
})->with([ | |
['https://youtu.be/dQw4w9WgXcQ', 'dQw4w9WgXcQ'], | |
['https://www.youtube.com/watch?v=dQw4w9WgXcQ', 'dQw4w9WgXcQ'], | |
['http://youtube.com/v/dQw4w9WgXcQ', 'dQw4w9WgXcQ'], | |
['https://www.youtube.com/embed/dQw4w9WgXcQ', 'dQw4w9WgXcQ'], | |
['https://www.youtube.com/shorts/dQw4w9WgXcQ', 'dQw4w9WgXcQ'], | |
['https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=1s', 'dQw4w9WgXcQ'], | |
['https://www.youtube.com/watch?v=dQw4w9WgXcQ&ab_channel=RickAstley', 'dQw4w9WgXcQ'], | |
[null, null], | |
['', null], | |
['https://example.com/watch?v=dQw4w9WgXcQ', null], | |
]); | |
it('returns null for invalid URLs', function ($url) { | |
expect(get_youtube_video_id($url))->toBeNull(); | |
})->with([ | |
'invalid URL' => ['https://example.com'], | |
'empty URL' => [''], | |
'null URL' => [null], | |
'not a YouTube URL' => ['https://vimeo.com/123456'], | |
]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment