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.

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 šŸ˜‰

  • 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> by using this tags.