Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract YouTube ID from this Url

Tags:

regex

php

youtube

How can I extract a YouTube ID from this URL?

https%253A%252F%252Fwww.youtube.com%252Fwatch%253Fv%253Dnn5hCEMyE-E

I tried this regex:

$url = $_GET["q"];
preg_match("/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'>]+)/", $url, $matches);
like image 492
dLehr Avatar asked Dec 01 '22 13:12

dLehr


1 Answers

Decode it first and use the second index ([1]) of array matches:

if(isset($_GET["q"]))
{
    $url = urldecode(rawurldecode($_GET["q"]));
    # https://www.youtube.com/watch?v=nn5hCEMyE-E
    preg_match("/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'>]+)/", $url, $matches);
    echo $matches[1];
    # nn5hCEMyE-E
}
like image 140
Pedro Lobito Avatar answered Dec 06 '22 00:12

Pedro Lobito