PHP Regex 获取 youtube 视频 ID?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3392993/
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-25 09:34:59  来源:igfitidea点击:

PHP Regex to get youtube video ID?

phpregex

提问by wesbos

Can someone show me how to get the youtube id out of a url regardless of what other GET variables are in the URL.

有人可以告诉我如何从 url 中获取 youtube id,而不管 URL 中有哪些其他 GET 变量。

Use this video for example: http://www.youtube.com/watch?v=C4kxS1ksqtw&feature=related
So between v=and before the next &

例如使用此视频:http://www.youtube.com/watch?v=C4kxS1ksqtw&feature=related
因此v=在下一个之间和之前&

回答by Peter Ajtai

Use parse_url()and parse_str().

使用 parse_url()parse_str()

(You can use regexes for just about anything, but they are very easy to make an error in, so if there are PHP functions specifically for what you are trying to accomplish, use those.)

(您几乎可以将正则表达式用于任何事情,但它们很容易出错,因此如果有专门针对您要完成的任务的 PHP 函数,请使用它们。)

parse_url takes a string and cuts it up into an array that has a bunch of info. You can work with this array, or you can specify the one item you want as a second argument. In this case we're interested in the query, which is PHP_URL_QUERY.

parse_url 接受一个字符串并将其切割成一个包含一堆信息的数组。您可以使用此数组,也可以指定您想要的一项作为第二个参数。在这种情况下,我们对查询感兴趣,即PHP_URL_QUERY.

Now we have the query, which is v=C4kxS1ksqtw&feature=relate, but we only want the part after v=. For this we turn to parse_strwhich basically works like GETon a string. It takes a string and creates the variables specified in the string. In this case $vand $featureis created. We're only interested in $v.

现在我们有了查询,即v=C4kxS1ksqtw&feature=relate,但我们只需要 之后的部分v=。为此,我们转向parse_str它基本上像GET在字符串上一样工作。它接受一个字符串并创建字符串中指定的变量。在这种情况下,$v$feature被创建。我们只对$v.

To be safe, you don't want to just store all the variables from the parse_urlin your namespace (see mellowsoon's comment). Instead store the variables as elements of an array, so that you have control over what variables you are storing, and you cannot accidentally overwrite an existing variable.

为安全起见,您不想只将所有变量存储parse_url在您的命名空间中(请参阅 mellowsoon 的评论)。而是将变量存储为数组的元素,以便您可以控制要存储的变量,并且不会意外覆盖现有变量。

Putting everything together, we have:

把所有东西放在一起,我们有:

<?php
$url = "http://www.youtube.com/watch?v=C4kxS1ksqtw&feature=relate";
parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
echo $my_array_of_vars['v'];    
  // Output: C4kxS1ksqtw
?> 

Working example

工作示例



Edit:

编辑:

hehe - thanks Charles. That made me laugh, I've never seen the Zawinski quote before:

呵呵——谢谢查尔斯。这让我发笑,我以前从未见过 Zawinski 的话:

Some people, when confronted with a problem, think ‘I know, I'll use regular expressions.' Now they have two problems.Jamie Zawinski

Some people, when confronted with a problem, think ‘I know, I'll use regular expressions.' Now they have two problems.杰米扎温斯基

回答by Anthony Leach

preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $url, $matches);

This will account for

这将占

youtube.com/v/{vidid}
youtube.com/vi/{vidid}
youtube.com/?v={vidid}
youtube.com/?vi={vidid}
youtube.com/watch?v={vidid}
youtube.com/watch?vi={vidid}
youtu.be/{vidid}

I improved it slightly to support: http://www.youtube.com/v/5xADESocujo?feature=autoshare&version=3&autohide=1&autoplay=1

我稍微改进了它以支持:http: //www.youtube.com/v/5xADESocujo?feature=autoshare&version=3&autohide=1&autoplay=1

The line I use now is:

我现在使用的线路是:

preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+(?=\?)|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $link, $matches);

回答by Shawn

Based on bokor's comment on Anthony's answer:

基于 bokor 对 Anthony 回答的评论:

preg_match("/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'>]+)/", $url, $matches);

$matches[1]contains the vidid

$matches[1]包含视频

Matches:

火柴:

Does not match:

不匹配:

  • www.facebook.com?wtv=youtube.com/v/vidid
  • www.facebook.com?wtv=youtube.com/v/vidid

回答by Kus

This can be very easily accomplished using parse_strand parse_urland is more reliable in my opinion.

这可以使用parse_strparse_url很容易地完成,在我看来更可靠。

My function supports the following urls:

我的函数支持以下网址:

Also includes the test below the function.

还包括下面的测试功能。

/**
 * Get Youtube video ID from URL
 *
 * @param string $url
 * @return mixed Youtube video ID or FALSE if not found
 */
function getYoutubeIdFromUrl($url) {
    $parts = parse_url($url);
    if(isset($parts['query'])){
        parse_str($parts['query'], $qs);
        if(isset($qs['v'])){
            return $qs['v'];
        }else if(isset($qs['vi'])){
            return $qs['vi'];
        }
    }
    if(isset($parts['path'])){
        $path = explode('/', trim($parts['path'], '/'));
        return $path[count($path)-1];
    }
    return false;
}
// Test
$urls = array(
    'http://youtube.com/v/dQw4w9WgXcQ?feature=youtube_gdata_player',
    'http://youtube.com/vi/dQw4w9WgXcQ?feature=youtube_gdata_player',
    'http://youtube.com/?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
    'http://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
    'http://youtube.com/?vi=dQw4w9WgXcQ&feature=youtube_gdata_player',
    'http://youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
    'http://youtube.com/watch?vi=dQw4w9WgXcQ&feature=youtube_gdata_player',
    'http://youtu.be/dQw4w9WgXcQ?feature=youtube_gdata_player'
);
foreach($urls as $url){
    echo $url . ' : ' . getYoutubeIdFromUrl($url) . "\n";
}

回答by T.Todua

SOLTUION For any link type!!:

解决方案对于任何链接类型!

<?php
function get_youtube_id_from_url($url)  {
     preg_match('/(http(s|):|)\/\/(www\.|)yout(.*?)\/(embed\/|watch.*?v=|)([a-z_A-Z0-9\-]{11})/i', $url, $results);    return $results[6];
}


echo get_youtube_id_from_url('http://www.youtube.com/watch?var1=blabla#v=GvJehZx3eQ1$var2=bla');
      // or                   http://youtu.be/GvJehZx3eQ1 
      // or                   http://www.youtube.com/embed/GvJehZx3eQ1
      // or                   http://www.youtu.be/GvJehZx3eQ1/blabla?xyz
?>

outputs:GvJehZx3eQ1

输出:GvJehZx3eQ1

回答by lleitep3

fixed based on How to validate youtube video ids?

基于如何验证 youtube 视频 ID修复

<?php

$links = [
    "youtube.com/v/tFad5gHoBjY",
    "youtube.com/vi/tFad5gHoBjY",
    "youtube.com/?v=tFad5gHoBjY",
    "youtube.com/?vi=tFad5gHoBjY",
    "youtube.com/watch?v=tFad5gHoBjY",
    "youtube.com/watch?vi=tFad5gHoBjY",
    "youtu.be/tFad5gHoBjY",
    "http://youtu.be/qokEYBNWA_0?t=30m26s",
    "youtube.com/v/vidid",
    "youtube.com/vi/vidid",
    "youtube.com/?v=vidid",
    "youtube.com/?vi=vidid",
    "youtube.com/watch?v=vidid",
    "youtube.com/watch?vi=vidid",
    "youtu.be/vidid",
    "youtube.com/embed/vidid",
    "http://youtube.com/v/vidid",
    "http://www.youtube.com/v/vidid",
    "https://www.youtube.com/v/vidid",
    "youtube.com/watch?v=vidid&wtv=wtv",
    "http://www.youtube.com/watch?dev=inprogress&v=vidid&feature=related",
    "youtube.com/watch?v=7HCZvhRAk-M"
];

foreach($links as $link){
    preg_match("#([\/|\?|&]vi?[\/|=]|youtu\.be\/|embed\/)([a-zA-Z0-9_-]+)#", $link, $matches);
    var_dump(end($matches));
}

回答by Krzysiek

We know that video ID is 11 chars length and can be preceded by v=or vi=or v/or vi/or youtu.be/. So the simplest way to do this:

我们知道视频 ID 的长度为 11 个字符,并且可以以v=orvi=v/orvi/开头youtu.be/。所以最简单的方法是:

<?php
$youtube = 'http://youtube.com/v/dQw4w9WgXcQ?feature=youtube_gdata_player
http://youtube.com/vi/dQw4w9WgXcQ?feature=youtube_gdata_player
http://youtube.com/?v=dQw4w9WgXcQ&feature=youtube_gdata_player
http://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player
http://youtube.com/?vi=dQw4w9WgXcQ&feature=youtube_gdata_player
http://youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player
http://youtube.com/watch?vi=dQw4w9WgXcQ&feature=youtube_gdata_player
http://youtu.be/dQw4w9WgXcQ?feature=youtube_gdata_player';

preg_match_all("#(?<=v=|v\/|vi=|vi\/|youtu.be\/)[a-zA-Z0-9_-]{11}#", $youtube, $matches);

var_dump($matches[0]);

And output:

和输出:

array(8) {
  [0]=>
  string(11) "dQw4w9WgXcQ"
  [1]=>
  string(11) "dQw4w9WgXcQ"
  [2]=>
  string(11) "dQw4w9WgXcQ"
  [3]=>
  string(11) "dQw4w9WgXcQ"
  [4]=>
  string(11) "dQw4w9WgXcQ"
  [5]=>
  string(11) "dQw4w9WgXcQ"
  [6]=>
  string(11) "dQw4w9WgXcQ"
  [7]=>
  string(11) "dQw4w9WgXcQ"
}

回答by John Max

The following will work for all youtube links

以下内容适用于所有 youtube 链接

<?php
    // Here is a sample of the URLs this regex matches: (there can be more content after the given URL that will be ignored)
    // http://youtu.be/dQw4w9WgXcQ
    // http://www.youtube.com/embed/dQw4w9WgXcQ
    // http://www.youtube.com/watch?v=dQw4w9WgXcQ
    // http://www.youtube.com/?v=dQw4w9WgXcQ
    // http://www.youtube.com/v/dQw4w9WgXcQ
    // http://www.youtube.com/e/dQw4w9WgXcQ
    // http://www.youtube.com/user/username#p/u/11/dQw4w9WgXcQ
    // http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/dQw4w9WgXcQ
    // http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ
    // http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ
    // It also works on the youtube-nocookie.com URL with the same above options.
    // It will also pull the ID from the URL in an embed code (both iframe and object tags)

$url = "https://www.youtube.com/watch?v=v2_MLFVdlQM";

    preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);

    $youtube_id = $match[1];

echo $youtube_id;
    ?>

回答by Foxinni

I had some post content I had to cipher throughout to get the Youtube ID out of. It happened to be in the form of the <iframe>embed code Youtube provides.

我有一些帖子内容,我必须全程加密才能从中获取 Youtube ID。它恰好是<iframe>Youtube 提供的嵌入代码的形式。

 <iframe src="http://www.youtube.com/embed/Zpk8pMz_Kgw?rel=0" frameborder="0" width="620" height="360"></iframe>

The following pattern I got from @rob above. The snippet does a foreachloop once the matches are found, and for a added bonus I linked it to the preview image found on Youtube. It could potentially match more types of Youtube embed types and urls:

我从上面的@rob 得到的以下模式。foreach一旦找到匹配项,该代码段就会循环一次,为了获得额外的奖励,我将其链接到了在 Youtube 上找到的预览图像。它可能匹配更多类型的 Youtube 嵌入类型和 url:

$pattern = '#(?<=(?:v|i)=)[a-zA-Z0-9-]+(?=&)|(?<=(?:v|i)\/)[^&\n]+|(?<=embed\/)[^"&\n]+|(?<=??(?:v|i)=)[^&\n]+|(?<=youtu.be\/)[^&\n]+#';

preg_match_all($pattern, $post_content, $matches);

foreach ($matches as $match) {
    $img = "<img src='http://img.youtube.com/vi/".str_replace('?rel=0','', $match[0])."/0.jpg' />";
    break;
}

Rob's profile: https://stackoverflow.com/users/149615/rob

Rob 的个人资料:https: //stackoverflow.com/users/149615/rob

回答by NullUserException

if (preg_match('![?&]{1}v=([^&]+)!', $url . '&', $m))
    $video_id = $m[1];