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:

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(""); /* outputs: Array ( [scheme] => http [host] => [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 */
Code language: PHP (php)

Regular Expression (not perfect)

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

$url = ""; $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="'.$matches[1].'?rel=0&hd=1" frameborder="0" allowfullscreen></iframe>'; }else{ // Show Error echo "This YouTube URL is not valid"; }
Code language: PHP (php)

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 😉

About Ricard Torres

Senior Front-end Software Engineer at Netcentric, from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.

@ricard_dev @ricard_dev

📝 Blog 🎙 Podcast

  • Hi, and for multiple url please ?

    $res = parse_url(“”);
    $res1 = parse_url(“”);
    $res2 = parse_url(“”);
    $res3 = parse_url(“”);

    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 ‘’ (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> if you need to.