Grab the video ID from YouTube URL?

前端 未结 5 1901
臣服心动
臣服心动 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: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'], '/');
      }
    }
    

提交回复
热议问题