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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9594943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:13:03  来源:igfitidea点击:

RegEx pattern to get the YouTube video ID from any YouTube URL

phpregexyoutubeyoutube-api

提问by Shackrock

Let's take these URLs as an example:

我们以这些 URL 为例:

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

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.

此 PHP 函数在情况 1 中无法正确获取 ID,但在情况 2 中会。情况 1 非常常见,其中任何内容都可能出现在 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;
}

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?

我在想的是,必须有一种方法可以让我只查找“v=”,无论它位于 URL 的哪个位置,然后在此之后获取字符。以这种方式,不需要复杂的 RegEx。这是离谱吗?关于起点的任何想法?

回答by user1236048

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
}

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

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

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

请注意,最后 $values = 视频的 id

回答by Starx

Instead of regex. I hightly recommend parse_url()and parse_str():

而不是正则表达式。我强烈推荐parse_url()parse_str()

$url = "http://www.youtube.com/watch?v=8GqqjVXhfMU&feature=youtube_gdata_player";
parse_str(parse_url( $url, PHP_URL_QUERY ), $vars );
echo $vars['v'];    

Done

完毕

回答by jeroen

You could just use parse_urland parse_str:

你可以只使用parse_urland parse_str

$query_string = parse_url($url, PHP_URL_QUERY);
parse_str($query_string);
echo $v;

回答by teezee

I have used the following patterns because YouTube has a youtube-nocookie.com domain too:

我使用了以下模式,因为 YouTube 也有一个 youtube-nocookie.com 域:

'@youtube(?:-nocookie)?\.com/watch[#\?].*?v=([^"\& ]+)@i',
'@youtube(?:-nocookie)?\.com/embed/([^"\&\? ]+)@i',
'@youtube(?:-nocookie)?\.com/v/([^"\&\? ]+)@i',
'@youtube(?:-nocookie)?\.com/\?v=([^"\& ]+)@i',
'@youtu\.be/([^"\&\? ]+)@i',
'@gdata\.youtube\.com/feeds/api/videos/([^"\&\? ]+)@i',

In your case it would only mean to extend the existing expressions with an optional (-nocookie) for the regular YouTube.com URL like so:

在您的情况下,这仅意味着使用常规 YouTube.com URL 的可选 (-nocookie) 扩展现有表达式,如下所示:

if (preg_match('/youtube(?:-nocookie)\.com\/watch\?v=([^\&\?\/]+)/', $url, $id)) {

If you change your proposed expression to NOT contain the final $, it should work like you intended. I added the -nocookie as well.

如果您将提议的表达式更改为不包含最后的 $,它应该会像您预期的那样工作。我也添加了 -nocookie。

/**
 * 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(?:-nocookie)?\.com  # or youtube.com and youtube-nocookie
          (?:           # 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;
}

回答by T.Todua

SOLUTION for any YOUTUBE LINK:

任何 YouTube 链接的解决方案:

http://youtube.com/v/dQw4w9WgXcQ
http://youtube.com/watch?v=dQw4w9WgXcQ
http://www.youtube.com/watch?feature=player&v=dQw4w9WgXcQ&var2=bla
http://youtu.be/dQw4w9WgXcQ

==

==

https://stackoverflow.com/a/20614061/2165415

https://stackoverflow.com/a/20614061/2165415

回答by Ante Braovic

Here is one solution

这是一种解决方案

/**
 * credits goes to: http://stackoverflow.com/questions/11438544/php-regex-for-youtube-video-id
 * update: mobile link detection
 */
public function parseYouTubeUrl($url)
{
     $pattern = '#^(?:https?://)?(?:www\.)?(?:m\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch\?v=|/watch\?.+&v=))([\w-]{11})(?:.+)?$#x';
     preg_match($pattern, $url, $matches);
     return (isset($matches[1])) ? $matches[1] : false;
}

It can deal with mobile links too.

它也可以处理移动链接。

回答by Morgon

Another easy way is using parse_str():

另一种简单的方法是使用parse_str()

<?php
    $url = 'http://www.youtube.com/watch?v=8GqqjVXhfMU&feature=youtube_gdata_player';
    parse_str($url, $yt);

    // The associative array $yt now contains all of the key-value pairs from the querystring (along with the base 'watch' URL, but doesn't seem you need that)
    echo $yt['v']; // echos '8GqqjVXhfMU';
?>

回答by Jacob Eggers

The parse_url suggestions are good. If you really want a regex you can use this:

parse_url 建议很好。如果你真的想要一个正则表达式,你可以使用这个:

/(?<=v=)[^&]+/`

回答by Mr. Kent

Here is my function for retrieving Youtube ID !

这是我检索 Youtube ID 的功能!

function getYouTubeId($url) {
    if (!(strpos($url, 'v=') !== false)) return false;
    $parse = explode('v=', $url);
    $code = $parse[1];
    if (strlen($code) < 11) return false;
    $code = substr($code, 0, 11);
    return $code;
}