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

How to Extract YouTube Video IDs from URLs with PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 06:34:02785browse

How to Extract YouTube Video IDs from URLs with PHP?

Extracting YouTube Video IDs with PHP

In web applications, it's often necessary to extract YouTube video IDs from user-entered URLs. Although the YouTube API does not provide a direct function for this task, there are alternative solutions.

One method is to use a regular expression to parse the URL string. Here's an example PHP function that does this:

<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>

For example, running echo youtube_id_from_url('http://youtu.be/NLqAF9hrVbY'); would output "NLqAF9hrVbY".

Another option is to use YouTube's oEmbed service. This provides metadata about the video, including the ID. Here's an example:

<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 oEmbed service provides additional information like the video title and thumbnail. However, the ID is not directly included in the response.

Ultimately, choosing which method to use depends on your specific needs. Using a regular expression is generally simpler, while the oEmbed service can provide more comprehensive information.

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