0

I am trying to get the video code from a youtube link like below:

https://www.youtube.com/watch?v=sLnwdjQQlIw

Specifically, I am trying to get the code that follows "v=".

The problem comes when the link looks like below:

https://youtu.be/OKuGTy7D52c

How would I go about getting the video code from that link?

Here is what I have so far:

<?php
    if(isset($_POST["Search"]))
    {
        $url = $_POST["URL"];
        $value = (explode('v=', $url));
        $videoId = $value[1];
    }
?>


<form method="post" class="form-group">
    <input name="url" type="url" class="form-control form-control-lg mb-3" placeholder="https://www.youtube.com/watch?v=9a5TF2U-Fa4" required>
    <button style="background-color:#f2ae06;border:none" name="Search" class="btn btn-primary btn-lg btn-block">Get</button>
</form>
Martin
  • 22,212
  • 11
  • 70
  • 132
  • Strip `https://youtu.be/` from the string using `str_replace()`? Use `parse_url($url, PHP_URL_PATH)` to get the path? – brombeer May 05 '20 at 13:08

2 Answers2

0

Work flow:

  • Check format of the given string.
  • Change how string is cut up, depending on format.

More simple version:

use str_ireplace and build an array of values you want to remove from the string. You will also want to use preg_replace to REGEX remove any Query String Appends (QSA) such as a timestart (?t=23) for example:

$remove = []; // array
$remove[] = 'https://www.youtube.com/watch?v=';
$remove[] = 'https://youtu.be/';
$remove[] = 'https://www.burning-kittens.com/video='; // etc. etc. 

// replaces each array values in string with nothing. 
$url = str_ireplace($remove, '', $url); 

// Use Regex to remove any query string appends such as start time etc.
// https://youtu.be/OKuGTy7D52c?t=23 removes the '?t=23' bit. 
$url = preg_replace('/(\?.*)/','',$url);
Community
  • 1
  • 1
Martin
  • 22,212
  • 11
  • 70
  • 132
  • @bigscreenplay if this is helpful you can "vote" for the answer using the up arrow at the top left, cheers `:-)` – Martin May 09 '20 at 19:31
0

You could use the solution from this thread: Get characters after last / in url

$pos = strrpos($url, '/');
$id = substr($url, strrpos($url, '/') + 1);
gnorman
  • 163
  • 10