-1

I want to fetch youtube video id from the URL but YouTube has many different patterns for the URL. I am getting thumbnails from one of the patterns which is (https://www.youtube.com/watch?v=4Wm6-8X3Vq4) but unable to get from this type of URL (https://youtu.be/HCjNJDNzw8Y) and this is my code. And I want this code should work for both of the URLs. Plz, Help!

if (isset($_POST["Submit"])) {
    $url = $_POST["url"];
    $value = explode('v=', $url);
    $videoId = $value[1];

} ?>
Prisoner
  • 49,922
  • 7
  • 53
  • 105
Rador
  • 3
  • 1

1 Answers1

0

We know that video ID is 11 chars length and can be preceded by v= or vi= or v/ or vi/ or youtu.be/ So the simplest way to do this:-

PHP Code:-

<?php
if(isset($_POST["Submit"])){
    $url = $_POST["url"];
    preg_match_all("#(?<=v=|v\/|vi=|vi\/|youtu.be\/)[a-zA-Z0-9_-]{11}#", $url, $matches);
echo $matches[0][0];

} 

?>

HTML FORM:-

<form method="post">

<input type="text" name="url"><br>

<input type="submit" name="Submit">

</form>
KUMAR
  • 1,993
  • 2
  • 9
  • 26