Youtube Iframe with full link

Hello!

I would like to know if there is any iframe or something like that that I can get by the video on my site, in the manageable case, usually the YouTube embed are with the video ID. I wonder if there are any 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 id of the video)

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

You can see that after the embed is entered the id of the video that is registered, only that do I need some embed that I might be pasting the entire youtube link, example:

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

I have been thinking about treating the URL, exploding and taking the data only after the = only that sometimes it can be registered the short URL of the video that ends up being like this: https://youtu.be/9ZyZxgGBfic it won't work out.

Author: Maurício Krüger, 2016-03-03

1 answers

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

<?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.

 3
Author: Guilherme Nascimento, 2017-05-23 12:37:32