Get a Youtube video ID from the URL

Asked

Viewed 7,268 times

12

4 answers

18


Can use parse_url to extract fragments from a url and match parse_str that converts a valid querystring into an associative array ($param).

<?php
$url = 'https://www.youtube.com/watch?v=Y3eZEtwQVI8&list=UUdm1fwk5iqteE0MVOBUuE8Q%22';
$itens = parse_url ($url);
parse_str($itens['query'], $params);

echo '<pre>';
print_r($params);

Exit:

Array
(
    [v] => Y3eZEtwQVI8
    [list] => UUdm1fwk5iqteE0MVOBUuE8Q"
)

Example

  • That I liked, for now is the only one that works regardless of how many parameters were provided, and the order of them. Just pick up the $params['v'] that the result will always be consistent.

  • 2

    Alternatively you can enter PHP_URL_QUERY as the second argument of parse_url() to have only querystring.

5

You can use the explode

$video  = "https://www.youtube.com/watch?v=jNQXAC9IVRw";
$id = explode("?v=", $video);

Other examples here

  • Thanks for the answer! But what if, by chance, the string were: "https://www.youtube.com/watch?v=Y3eZEtwQVI8&list=Udm1fwk5iqteE0MVOBUuE8Q" and I still wanted to take only the video ID? ; which would end in '&'?

3

Can use regex to extract the ID:

$patternRegex = "/http[s]?:\\/\\/www\\.youtube\\.com\\/watch\\?v=(\\w+)/";
$urlYoutube = "https://www.youtube.com/watch?v=jNQXAC9IVRw";

preg_match($patternRegex, $urlYoutube, $matches);

Behold here working with your example.

Explaining the $patternRegex:

  • /http[s]?:\\/\\/www\\.youtube\\.com\\/watch\\?v= : This part looks for the beginning of the URL.
  • [s]? - Indicates that the character s can occur one or zero times.
  • (\\w+)/ : This part captures all alphanumeric characters and underscores which exist after ?= v until the end of the URL.
  • 1

    A question: Every youtube url will have the https? If by any chance it comes with http, your regex no longer works.

  • You can change regex to support urls without SSL. See the edited response.

3

You can use as soon as any format of the url will work

function YoutubeID($url)
{
    if(strlen($url) > 11)
    {
        if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match)) 
        {
            return $match[1];
        }
        else
            return false;
    }
    return $url;
}
  • although the answer is not well detailed it works, congratulations.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.