Home  >  Article  >  Backend Development  >  How to Extract YouTube Video IDs from URLs Using PHP?

How to Extract YouTube Video IDs from URLs Using PHP?

Susan Sarandon
Susan SarandonOriginal
2024-10-31 08:20:38477browse

How to Extract YouTube Video IDs from URLs Using PHP?

How to Extract YouTube Video ID Using PHP

Introduction

Extracting YouTube video IDs from URLs is crucial for many applications. This allows developers to identify and process videos based on their unique IDs. While the YouTube API does not provide a direct function for this, there are other methods available.

Regex-Based Approach

A common solution involves using a regular expression to extract the video ID from the URL. The following function provides an implementation in PHP:

<code class="php">function youtube_id_from_url($url) {
    $pattern = '%^
        (?: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>

Example Usage

To use the function, simply pass the YouTube URL as a parameter:

<code class="php">$video_id = youtube_id_from_url('http://youtu.be/NLqAF9hrVbY');
echo $video_id; // NLqAF9hrVbY</code>

YouTube oEmbed Service

While not directly an API function, YouTube offers an oEmbed service. By making a request to a specific URL with the video URL as a parameter, you can retrieve additional information about the video, including its ID. This method may provide more context and allow for URL validation.

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

The above is the detailed content of How to Extract YouTube Video IDs from URLs Using PHP?. 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