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.

Regular Expression (not perfect)

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

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.

*
*