【问题标题】:How to extract YouTube ID from this Url如何从此 URL 中提取 YouTube ID
【发布时间】:2016-09-08 05:52:11
【问题描述】:

如何从该 URL 中提取 YouTube ID?

https%253A%252F%252Fwww.youtube.com%252Fwatch%253Fv%253Dnn5hCEMyE-E

我试过这个正则表达式:

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

【问题讨论】:

    标签: php regex youtube


    【解决方案1】:

    先解码并使用数组matches的第二个索引([1]):

    if(isset($_GET["q"]))
    {
        $url = urldecode(rawurldecode($_GET["q"]));
        # https://www.youtube.com/watch?v=nn5hCEMyE-E
        preg_match("/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'>]+)/", $url, $matches);
        echo $matches[1];
        # nn5hCEMyE-E
    }
    

    【讨论】:

      【解决方案2】:

      试试这个(在传递给函数之前不要忘记 make urldecode(rawurldecode($url))

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-24
        • 2017-02-08
        • 2023-03-27
        • 2018-12-12
        • 2019-12-27
        • 2012-05-22
        • 2011-03-28
        相关资源
        最近更新 更多