Get ID of a YouTube video by URL

12

I have this string " link " and I want to get only the ID, ie from "? v="     

asked by anonymous 12.12.2014 / 17:08

4 answers

14

You can use parse_url to extract the fragments of a url and match it with parse_str that converts a valid querystring to 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);

Output:

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

Example

    
12.12.2014 / 17:31
5

You can use explode

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

Other examples here

    
12.12.2014 / 17:21
3

You 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);

See here to work with your example.

Explaining $patternRegex :

  • /http[s]?:\/\/www\.youtube\.com\/watch\?v= : This part looks for the start of the URL.
  • [s]? - Indicates that the character s can occur once or zero times.
  • (\w+)/ : This part captures all alphanumeric characters and underscores that exist after the? = v to the end of the URL.
12.12.2014 / 17:19
3

You can use as any url format 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;
}
    
13.12.2014 / 03:28