Youtube iframe with full link

Asked

Viewed 840 times

0

Hello!

I wonder if there is any iframe or something like that I can get video on my site, in manageable case, usually youtube embed are with video ID. I wonder if there is one that I can paste the entire Youtube url that works on the page. Follow the example of what I use(remembering that this I copy only the video id)

 <iframe width="100%" height="450" src="http://www.youtube.com/embed/<?php print $insti->video ?>"></iframe>

You can note that after the embed/embed is inserted the id of the video that is registered, only that I need some embed that I may be pasting the entire youtube link, example:

<iframe width="100%" height="450" src="https://www.youtube.com/watch?v=Z9VIEZhFORE"></iframe>

I was thinking about treating the URL, exploding and picking up the data only after = only sometimes the short URL of the video can be registered that ends up like this: https://youtu.be/9ZyZxgGBfic then it won’t work.

1 answer

3


If this takes the URL: <?php print $insti->video ?> then you can make a parse ID, a good example in Soen thus:

<?php
/**
 * get youtube video ID from URL
 *
 * @param string $url
 * @return string Youtube video id or FALSE if none found. 
 */
function youtube_id_from_url($url) {
    $pattern = 
        '%^# Match any youtube URL
        (?:https?://)?  # Optional scheme. Either http or https
        (?:www\.)?      # Optional www subdomain
        (?:             # Group host alternatives
          youtu\.be/    # Either youtu.be,
        | youtube\.com  # or youtube.com
          (?:           # Group path alternatives
            /embed/     # Either /embed/
          | /v/         # or /v/
          | /watch\?v=  # or /watch\?v=
          )             # End path alternatives.
        )               # End host alternatives.
        ([\w-]{10,12})  # Allow 10-12 for 11 char youtube id.
        $%x'
        ;
    $result = preg_match($pattern, $url, $matches);
    if ($result) {
        return $matches[1];
    }
    return false;
}
?>

<iframe width="100%" height="450" src="http://www.youtube.com/embed/<?php echo youtube_id_from_url($insti->video); ?>"></iframe>

It supports any Youtube url, including embed and short.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.