Youtube API: Extracting Video ID from URL
Introduction
When working with Youtube videos in web applications, it becomes necessary to extract the video ID from the URL to access its metadata and embed it. Youtube API does not provide a direct function for this task, so alternative methods must be employed.
Using Regular Expressions
One approach is to use regular expressions to parse the URL and identify the video ID. Here's a function written in PHP:
<code class="php">function youtube_id_from_url($url) { $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/ | /watch\?v= # or /watch\?v= ) # End path alternatives. ) # End host alternatives. ([\w-]{10,12}) # Allow 10-12 for 11 char youtube id. $%x'; $result = preg_match($pattern, $url, $matches); if ($result) { return $matches[1]; } return false; }</code>
Youtube OEMBED Service
Another option is to utilize Youtube's OEMBED service, which provides additional information about the video, including its ID. Here's how to use it:
<code class="php">$url = 'http://youtu.be/NLqAF9hrVbY'; var_dump(json_decode(file_get_contents(sprintf('http://www.youtube.com/oembed?url=%s&format=json', urlencode($url)))));</code>
Additional Considerations
The above is the detailed content of How to Extract a Video ID from a YouTube URL?. For more information, please follow other related articles on the PHP Chinese website!