从任何 YouTube URL 获取 YouTube 视频 ID 的 RegEx 模式

2022-01-06 00:00:00 regex youtube youtube-api php

让我们以这些 URL 为例:

Let's take these URLs as an example:

  1. http://www.youtube.com/watch?v=8GqqjVXhfMU&feature=youtube_gdata_player
  2. http://www.youtube.com/watch?v=8GqqjVXhfMU

此 PHP 函数在第 1 种情况下无法正确获取 ID,但会在第 2 种情况下正确获取 ID.第 1 种情况非常常见,其中任何内容都可能出现在 YouTube ID 后面.

This PHP function will NOT properly obtain the ID in case 1, but will in case 2. Case 1 is very common, where ANYTHING can come behind the YouTube ID.

/**
 * 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 (false !== $result) {
        return $matches[1];
    }
    return false;
}

我的想法是,必须有一种方法可以让我只查找v=",无论它位于 URL 的哪个位置,然后获取后面的字符.以这种方式,不需要复杂的 RegEx.这是离谱吗?对起点有什么想法吗?

What I'm thinking is that there must be a way where I can just look for the "v=", no matter where it lies in the URL, and take the characters after that. In this manner, no complex RegEx will be needed. Is this off base? Any ideas for starting points?

推荐答案

if (preg_match('/youtube.com/watch?v=([^&?/]+)/', $url, $id)) {
  $values = $id[1];
} else if (preg_match('/youtube.com/embed/([^&?/]+)/', $url, $id)) {
  $values = $id[1];
} else if (preg_match('/youtube.com/v/([^&?/]+)/', $url, $id)) {
  $values = $id[1];
} else if (preg_match('/youtu.be/([^&?/]+)/', $url, $id)) {
  $values = $id[1];
}
else if (preg_match('/youtube.com/verify_age?next_url=/watch%3Fv%3D([^&?/]+)/', $url, $id)) {
    $values = $id[1];
} else {   
// not an youtube video
}

这是我用来从 youtube 网址中提取 id 的方法.我认为它适用于所有情况.

This is what I use to extract the id from an youtube url. I think it works in all cases.

注意最后 $values = 视频的 id

Note that at the end $values = id of the video

相关文章