How to parse YouTube ID from the URL

Situation: you want to allow your users to post YouTube vĂ­deos but you don't want them to post iframes or javascript.

Well there is but a simple solution.

From URL

From an URL like this: http://www.youtube.com/watch?v=te5i_CIC9Po

We want the te5i_CIC9Po part.

Parse URL (best)

Parse the URL and get the video ID. You can use it to create a video iframe.

>$res = parse_url("http://www.youtube.com/watch?v=tcSqqAY-6Vo"); /* outputs: Array ( [scheme] => http [host] => www.youtube.com [path] => /watch [query] => v=tcSqqAY-6Vo ) */ // make sure we get only the 11 characters from the video ID. $video_id = substr($res['query'], 2, 11); /* Ouput $video_id = tcSqqAY-6Vo */

Regular Expression (not perfect)

This other method works in most of the cases. It uses the PHP's preg_match function.

$url = "http://www.youtube.com/watch?v=te5i_CIC9Po"; $test = preg_match("/http\:\/\/www\.youtube\.com\/watch\?v=(\w{11})/", $url, $matches); if(sizeof($matches)>0){ // Ok good to go $youtube_iframe='<iframe title="YouTube video player" width="500" height="311" src="http://www.youtube.com/embed/'.$matches[1].'?rel=0&hd=1" frameborder="0" allowfullscreen></iframe>'; }else{ // Show Error echo "This YouTube URL is not valid"; }

The code above will scan the given YouTube URL and check if it has a valid format.

Then it will add the ID to the iframe. You can save it and show it whereever you want 😉

2 comments
  • Hi, and for multiple url please ?

    $res = parse_url(“http://www.youtube.com/watch?v=_7LK39icw6M&hd=1&t=1s”);
    $res1 = parse_url(“http://www.youtube.com/watch?v=tcSqqAY-6Vo”);
    $res2 = parse_url(“http://youtu.be/_7LK39icw6M”);
    $res3 = parse_url(“http://www.youtube.com/embed/3QByfthwPYU?rel=0”);

    array (size=4)
    ‘path’ => string ‘/watch’ (length=6)
    ‘query’ => string ‘v=_7LK39icw6M&hd=1&t=1s’ (length=23)

    array (size=4)
    ‘path’ => string ‘/watch’ (length=6)
    ‘query’ => string ‘v=tcSqqAY-6Vo’ (length=13)

    array (size=3)
    ‘host’ => string ‘youtu.be’ (length=8)
    ‘path’ => string ‘/_7LK39icw6M’ (length=12)

    array (size=4)
    ‘path’ => string ‘/embed/3QByfthwPYU’ (length=18)
    ‘query’ => string ‘rel=0’ (length=5)

    No perfect :/

Leave a Reply

Add <code> Some Code </code> by using this tags.

*
*