1

I have a function that parses a YouTube URL to retrieve the video id and then it generates a clean embed code for most use cases. The embed breaks if I pass it a URL where time_continue exists such as https://www.youtube.com/watch?time_continue=79&v=2uBDNhe6Gkk&feature=emb_title

if(isset($_POST['submit'])){
$embedURL = mysqli_real_escape_string($con, $_POST['embedCode']);

function convertYoutube($string) {
  return preg_replace(
    "'#(?:https?:\/\/)?(?:m\.|www\.)?(?:youtu\.be\/|youtube\-nocookie\.com\/embed\/|youtube\.com\/(?:embed\/|v\/|e\/|\?v=|shared\?ci=|watch\?v=|watch\?.+&v=))([-_A-Za-z0-9]{10}[AEIMQUYcgkosw048])\S*#s'",
    "\https://www.youtube.com/embed/$2",
    $string
  );
}

$embedURL = convertYoutube($embedURL);
$embedCode = "<div class=''embed-responsive embed-responsive-16by9''><iframe class=''embed-responsive-item'' src=''$embedURL'' allowfullscreen></iframe></div>"; 
}

The code produces the following (it doesn't strip the time_continue and feature=emb_title parameters which I need removed).

<div class='embed-responsive embed-responsive-16by9'><iframe class='embed-responsive-item' src='https://www.youtube.com/watch?time_continue=79&v=2uBDNhe6Gkk&feature=emb_title' allowfullscreen></iframe></div>

I'd like the function to format it like embed code below without parameters. Thank you

<div class='embed-responsive embed-responsive-16by9'><iframe class='embed-responsive-item' src='https://www.youtube.com/embed/2uBDNhe6Gkk' allowfullscreen></iframe></div>
Jeremy Person
  • 171
  • 1
  • 3
  • 13

1 Answers1

2

This is taking parts of a few other questions already on SO, but as you have a combination of them, thought I would put and answer together instead of trying to explain it in a comment.

The first part would be to split the URL into it's parts using parse_url(). Then with the query part of the string, parse that with parse_str() to split out all of the parameters. Then just combine the relevant parts into the new URL...

$url_parts = parse_url($embedURL);
parse_str($url_parts['query'], $params);
$embedURL = $url_parts['scheme'] . '://' . $url_parts['host'] . 
        $url_parts['path']."/".$params['v'];

this gives...

https://www.youtube.com/watch/2uBDNhe6Gkk

To replace the watch with embed, just replace the 'path' part...

$embedURL = $url_parts['scheme'] . '://' . $url_parts['host'] . 
        "/embed/" . $params['v'];
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55