Latox
Latox

Reputation: 4705

Grab the video ID from YouTube URL?

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=embedded

I need a function just to grab the ID: KMU0tzLwhbE

I'm working with something like this at the moment:

$url = "http://www.youtube.com/watch?v=KMU0tzLwhbE";
parse_str(parse_url($url, PHP_URL_QUERY ), $youtubeURL);
echo $youtubeURL['v'];

But I need it to also work for the youtube.be link. Any suggestions on how to proceed would be greatly appreciated.

Upvotes: 1

Views: 1669

Answers (5)

Lasith
Lasith

Reputation: 565

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

Upvotes: 0

Ayman Safadi
Ayman Safadi

Reputation: 11552

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];

Upvotes: 2

Andrew Moore
Andrew Moore

Reputation: 95434

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

Upvotes: 1

Siva
Siva

Reputation: 1133

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'], '/');
  }
}

Upvotes: 1

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

Upvotes: 0

Related Questions