Home  >  Article  >  Backend Development  >  How Can I Extract Video IDs from YouTube URLs?

How Can I Extract Video IDs from YouTube URLs?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 07:05:02286browse

How Can I Extract Video IDs from YouTube URLs?

Extracting Video IDs from YouTube URLs

In scenarios where users provide YouTube video URLs, it becomes necessary to extract the video ID for various functionality. While the YouTube API does not offer a dedicated function for this purpose, alternative approaches are available.

One method involves using a regular expression to parse the URL and isolate the video ID. Here's an example PHP function utilizing this approach:

<code class="php">/**
 * get youtube video ID from URL
 *
 * @param string $url
 * @return string Youtube video id or FALSE if none found.
 */
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>

Another option is to leverage YouTube's oEmbed service. While it doesn't directly provide the video ID, it offers additional metadata about the URL. Here's an example using JSON:

<code class="php">$url = 'http://youtu.be/NLqAF9hrVbY';
var_dump(json_decode(file_get_contents(sprintf('http://www.youtube.com/oembed?url=%s&amp;format=json', urlencode($url)))));</code>

The above is the detailed content of How Can I Extract Video IDs from YouTube URLs?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn