0

I want to get the individual ID from a youtube link so that I can use it later on, to pull other information such as its thumbnail image and insert it into the embedded iframe.

I notice there that all, I hope, of the urls on youtube start http://www.youtube.com/watch?v= Unique video ID and then depending on a few things can end something like &list=RD02M5u5zXVmoHM. But the unique id always has a & after it and the watch?v= before. Is this the best way to do it? Have a written this correctly?

$link=$_POST['link'];
$link_id=str_replace('http://www.youtube.com/watch?v=', '', $link);
$link_id=strstr($link_id, '&', true);

This comes from form data. Is there anything other variables from youtube URLs I may encounter?

Adam Brown
  • 2,812
  • 4
  • 28
  • 39

2 Answers2

1

A combination of parse_url() and parse_str() would be a simpler way where PHP handles the dirty work for you. Example:

$video_id = false;

$url_parts = parse_url($link);
$query_params = array();

if (isset($url_parts['query']))
{
    parse_str($url_parts['query'], $query_params);
}

if (isset($query_params['v']))
{
    $video_id = $query_params['v'];
}

And now $video_id contains the ID you need.

pilsetnieks
  • 10,330
  • 12
  • 48
  • 60
1

What you want to do is use: http://php.net/pase_url and http://php.net/parse_str like this:

<?php
$info = parse_url("https://www.youtube.com/watch?v=DA57FOJSdM8");
parse_str($info["query"], $query);
print_r($query);

// Outputs: Array ( [v] => DA57FOJSdM8 )
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338