【问题标题】:RegEx pattern to get the YouTube video ID from any YouTube URL用于从任何 YouTube URL 获取 YouTube 视频 ID 的 RegEx 模式
【发布时间】:2012-03-24 14:16:57
【问题描述】:

我们以这些网址为例:

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

此 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;
}

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

【问题讨论】:

  • 我认为这种模式的主要问题只是模式末尾的 $ ,它将模式锚定在被测试字符串的末尾。这就是案例 1 不匹配的原因,因为它不以 ID 结尾。

标签: php regex youtube youtube-api


【解决方案1】:

这是我检索 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;
}

【讨论】:

    【解决方案2】:
    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 url 中提取 id 的方法。我认为它适用于所有情况。

    注意最后 $values = 视频的 id

    【讨论】:

    • 这是更为通用的方法,它涵盖了您将从/到 YouTube 获得的各种 URL 形式。 +1
    • @Bendoh 为什么这比带有parse_str 的选定答案更笼统 - 似乎它完美地捕获了 URL 中的每个变量?
    • 所选答案不会捕获 /v/ 或 embed/ 形式的 URL,只会捕获包含“v”作为查询参数的形式。它也不关注链接的主机名——它只是从查询字符串中带有“v”参数的任何 URL 中提取“v”的值。例如,youtube.com/v/ihCbVT637aM 将无法正确解析。
    • @Bendoh - 你是对的......谢谢。我已将此更改为“最佳答案”。
    • 有人知道这个对于 javascript 的等价物吗?
    【解决方案3】:

    这是一种解决方案

    /**
     * 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;
    }
    

    它也可以处理移动链接。

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        【解决方案5】:

        我使用了以下模式,因为 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',
        

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

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

        如果您将建议的表达式更改为不包含最后的 $,它应该会像您预期的那样工作。我也添加了 -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;
        }
        

        【讨论】:

          【解决方案6】:

          而不是正则表达式。我强烈推荐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'];    
          

          完成

          【讨论】:

            【解决方案7】:

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

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

            【讨论】:

              【解决方案8】:

              另一种简单的方法是使用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';
              ?>
              

              【讨论】:

              • 看起来您首先缺少 parse_url ,正如其他答案所述。使用 parse_url 它可以工作。仅供参考
              • [ORIG:没有必要解析_url。有人可能会说它更干净,但是 - 至少在 PHP 5.3.6 中 - 查询字符串参数之前的 URL 只是数组中的一个键。] - 编辑:啊,该死的,这在只有一个 QS 参数时有效,但是函数必须在 & 上拆分。 parse_url 将是更正确的方法。
              【解决方案9】:

              您可以只使用parse_url 和parse_str:

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

              【讨论】:

                猜你喜欢
                • 2017-08-17
                • 2016-04-22
                • 2011-03-24
                • 1970-01-01
                • 2012-05-22
                • 2011-03-28
                • 2011-05-02
                • 2016-01-21
                相关资源
                最近更新 更多