Grab the video ID from YouTube URL?

前端 未结 5 1893
臣服心动
臣服心动 2021-01-23 11:38

Say I have a list of IDs like so:

http://www.youtube.com/watch?v=KMU0tzLwhbE
http://youtu.be/KMU0tzLwhbE
http://www.youtube.com/watch?v=KMU0tzLwhbE&featured=         


        
相关标签:
5条回答
  • 2021-01-23 12:17

    Try something like:

    $pattern = '/(?:(?:\?|&)v=|\/)([A-Za-z0-9]{11})/';
    $url     = 'http://www.youtube.com/watch?v=KMU0tzLwhbE';
    
    preg_match($pattern, $url, $matches);
    
    echo $matches[1];
    
    0 讨论(0)
  • 2021-01-23 12:18

    The first group of a preg_match using (?:(?:\?|&)v=|youtu\.be\/)(.+?)(?:$|&) as the pattern.

    0 讨论(0)
  • 2021-01-23 12:21

    Try this:

    $video_url = "http://www.youtube.com/watch?v=KMU0tzLwhbE"; // http://youtu.be/KMU0tzLwhbE
    $url_parts = parse_url($video_url);
    
    if (isset($url_parts["query"]) && (strpos($url_parts["query"], "v") !== false)) {
      parse_str($url_parts["query"], $vars);
    
      // Handle full URLs with query string like 'http://www.youtube.com/watch?v=KMU0tzLwhbE'
      if (isset($vars["v"]) && $vars["v"]) {
        $video_code = $vars["v"];
    
      // Handle the new short URLs like 'http://youtu.be/KMU0tzLwhbE'
      } else if ($url_parts['path']) {
        $video_code = trim($url_parts['path'], '/');
      }
    }
    
    0 讨论(0)
  • 2021-01-23 12:37

    Simply im using this, because url is same for all youtube videos

    $ytid = str_replace('http://www.youtube.com/watch?v=', '','http://www.youtube.com/watch?v=bZP4nUFVC6s' );
    

    you can check for the other url variations as well

    0 讨论(0)
  • 2021-01-23 12:38

    Do not use regexes for this. URIs have a particular grammar and PHP gives you the tools required to parse each URL properly. See parse_url() and parse_str().

    <?php
    function getYoutubeVideoId($url) {
        $urlParts = parse_url($url);
    
        if($urlParts === false || !isset($urlParts['host']))
            return false;
    
        if(strtolower($urlParts['host']) === 'youtu.be')
            return ltrim($urlParts['path'], '/');
    
        if(preg_match('/^(?:www\.)?youtube\.com$/i', $urlParts['host']) && isset($urlParts['query'])) {
            parse_str($urlParts['query'], $queryParts);
    
            if(isset($queryParts['v']))
                return $queryParts['v'];
        }
    
        return false;
    }
    
    0 讨论(0)
提交回复
热议问题