How to Get Youtube Video Id from URL in PHP?

Get Youtube Video Id from Youtube Video URL in PHP, PHP Regex to get youtube video ID, Extract the YouTube Video ID from a URL Using PHP

Hi friends Today, I will tell you through this tutorial that you can get the id of video from youtube video url via php script code.

I will tell you to get the id of youtube video in 3 ways. So let’s try to understand this by example.

Example 1 :

<?php 
$link = "http://www.youtube.com/watch?v=jiXdSJYRHA0";
$video_id = explode("?v=", $link);
echo $video_id = $video_id[1];
?>

Example 2:

<?php
// Here is a sample of the URLs this regex matches: (there can be more content after the given URL that will be ignored)
// $url = http://youtu.be/dQw4w9WgXcQ
// $url = http://www.youtube.com/embed/dQw4w9WgXcQ
// $url = http://www.youtube.com/watch?v=dQw4w9WgXcQ
// $url = http://www.youtube.com/?v=dQw4w9WgXcQ
preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);
echo $youtube_id = $match[1];
?>

Example 3:

<?php 
$link = "http://www.youtube.com/watch?v=oHg5SJYRHA0&lololo";
$video_id = explode("?v=", $link); // For videos like http://www.youtube.com/watch?v=...
if (empty($video_id[1]))
$video_id = explode("/v/", $link); // For videos like http://www.youtube.com/watch/v/..
$video_id = explode("&", $video_id[1]); // Deleting any other params
$video_id = $video_id[0];
?>