Home > Backend Development > PHP Tutorial > How to Extract a Video ID from a YouTube URL?

How to Extract a Video ID from a YouTube URL?

Barbara Streisand
Release: 2024-10-31 23:04:28
Original
246 people have browsed it

How to Extract a Video ID from a YouTube URL?

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>
Copy after login

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&amp;format=json', urlencode($url)))));</code>
Copy after login

Additional Considerations

  • The example regular expression supports URLs for videos, playlists, and channels.
  • It handles various URL formats, including those with query parameters.
  • Using OEMBED is a valid alternative, but the ID has to be extracted from the returned JSON response.
  • Other coding languages will have their own approaches for parsing URLs and extracting video IDs.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template