0

I have a script that allows to grab videos from YouTube. However, it doesn't work if I use short URLs.

I think the problem is caused by the code that gets YouTube Id from URLs. Here are the lines I think are responsible for that:

$youtube_url = $_POST['file'];
$ParseUrl = parse_url($youtube_url);
parse_str($ParseUrl['query'], $youtube_url_prop);
$YouTubeId = isset($youtube_url_prop['v']) ? $youtube_url_prop['v'] : '';

I'm a newbie so first I would like to make sure that this is the code I should focus on.

If it so I hope someone can advice me how to change that lines to get YouTube Id also from short URLs.

Cheers.

1 Answers1

0

This a function that will give you the video id for the both url format :

<?php

function extractVideoId($url) {
    $re = '/(youtu\.be\/|youtube\.com\/(watch\?(.*&)?v=|(embed|v)\/))([^\?&"\'>]+)/';
    preg_match($re, $url, $matches, PREG_OFFSET_CAPTURE, 0);

    if(!isset($matches[5])) {
        return null;
    }
    return $matches[5][0];
}


$fullUrl ="https://www.youtube.com/watch?v=dQw4w9WgXcQ";
$shortUrl ="https://youtu.be/dQw4w9WgXcQ";

var_dump(extractVideoId($fullUrl));
var_dump(extractVideoId($shortUrl));

Output :

string(11) "dQw4w9WgXcQ"
string(11) "dQw4w9WgXcQ"
Ugo T.
  • 1,068
  • 8
  • 12
  • Thanks a lot. Works great. – adam1000018 May 07 '19 at 15:56
  • Hi @adam1000018 if this or any answer has solved your question please consider [accepting it](https://meta.stackexchange.com/q/5234/179419) by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this. Thanks ! – Ugo T. May 08 '19 at 12:44