Simple PHP Regex to get YouTube Video ID from URL easily, all youtube links support, youtube shortlink, youtube link with parameters, normal youtube link, and get youtube video id in javascript.

How To Get YouTube Video ID From URL

Using preg_replace() function we will get youtube video id from all youtube links.

Get YouTube Video ID

Use this code:

<?php
/* Regex to get YouTube ID Video Regex Written By Qassim Hassan wp-time.com | wp-plugins.in | qass.im | Twitter @QQQHZ */

// YouTube Video Link, or short video link http://youtu.be/sd0grLQ4voU or youtube video link with parameters https://www.youtube.com/watch?v=sd0grLQ4voU&index=200
$youtubeLink = "https://www.youtube.com/watch?v=sd0grLQ4voU";

// Regex to get YouTube Id Video
$youtubeRegex = preg_replace("/(https?)?+(:\/\/?)?+(www.?)?+[a-zA-Z]+(.com|.be)+(\/)+(watch?)?+[(?)]?+(v=?|V=?)?|(&)+(.*)/", "", $youtubeLink); // Regex by Qassim Hassan

// Get ID
echo $youtubeRegex;

?>

Now if youtube link is normal like this or shortlink like this or link with parameters like this, anyway you will get video ID.

Other Way

Get youtube video ID using other way, using explode() function and preg_replace() function:

// By Qassim Hassan

// If long youtube video link

$video = "https://www.youtube.com/watch?v=sd0grLQ4voU";
$video_id = explode("v=", preg_replace("/(&)+(.*)/", null, $video) );
echo $video_id[1];

And if short youtube video link:

// By Qassim Hassan

$video = "http://youtu.be/sd0grLQ4voU";
$video_id = explode("/", preg_replace("/(&)+(.*)/", null, $video) );
echo $video_id[3];

Full code:

// By Qassim Hassan

$video = "https://www.youtube.com/watch?v=sd0grLQ4voU";

if( preg_match("/(youtube.com)/", $video) ){ // if long youtube video link, like https://www.youtube.com/watch?v=sd0grLQ4voU
    $video_id = explode("v=", preg_replace("/(&)+(.*)/", null, $video) );
    echo $video_id[1];
}

else{
    if( preg_match("/(youtu.be)/", $video) ){ // if short youtube video link, like http://youtu.be/sd0grLQ4voU
        $video_id = explode("/", preg_replace("/(&)+(.*)/", null, $video) );
        echo $video_id[3];
    }
}

Get YouTube Video ID In JavaScript

// By Qassim Hassan

var youtubeLink = "https://www.youtube.com/watch?v=sd0grLQ4voU";

if( youtubeLink.match(/(youtube.com)/) ){
    var split_c = "v=";
    var split_n = 1;
}

if( youtubeLink.match(/(youtu.be)/) ){
    var split_c = "/";
    var split_n = 3;
}

var getYouTubeVideoID = youtubeLink.split(split_c)[split_n];

var cleanVideoID = getYouTubeVideoID.replace(/(&)+(.*)/, ""); // This is YouTube video ID.

Enjoy.