How Can I Extract Video IDs from YouTube URLs?

Susan Sarandon
Release: 2024-11-01 07:05:02
Original
285 people have browsed it

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!