High Clever
High Clever

Reputation: 55

How to parse YouTube video ID?

I need the ID of the YouTube video link. How to parse with PHP?

First link: https://www.youtube.com/watch?v=sEhy-RXkNo0

Second link: https://youtu.be/sEhy-RXkNo0

Upvotes: 1

Views: 1336

Answers (2)

b0ne
b0ne

Reputation: 655

Since the link won't always be in the nice format and may have another GET values it's better to use regex.

<?php
    $link1 = "https://www.youtube.com/watch?v=sEhy-RXkNo0";
    $link2 = "https://www.youtu.be/sEhy-RXkNo0";

    preg_match("/\?v=([^&]+)/", $link1, $id1);
    preg_match("/youtu.be\/([^&]+)/", $link2, $id2);

    $id1 = (isset($id1[1])) ? ($id1[1]) : (NULL);
    $id2 = (isset($id2[1])) ? ($id2[1]) : (NULL);

Upvotes: 2

Vishnu Bhadoriya
Vishnu Bhadoriya

Reputation: 1676

$data = " https://www.youtube.com/watch?v=sEhy-RXkNo0";    //youtube link

$data2 = "https://youtu.be/sEhy-RXkNo0"; 

$link= substr($data, strpos($data, "v=") + 2);  //for first link
$anotherLink = substr($data, strpos($data, "e/") + 2);   //for secondlink

Upvotes: 0

Related Questions