Get Youtube Video ID from html code with PHP

后端 未结 5 1897
小蘑菇
小蘑菇 2020-11-27 06:49

I want to get all only youtube video ID from html code

look the (or multiple) object/embed code for youtube video

// html from database

    &         


        
相关标签:
5条回答
  • 2020-11-27 07:15

    Brazenly stolen from htmlpurifier's youtube plugin:

    preg_match('#<object[^>]+>.+?http://www.youtube.com/v/([A-Za-z0-9\-_]+).+?</object>#s', $markup, $matches);
    var_dump($matches[1]);
    
    0 讨论(0)
  • 2020-11-27 07:15

    Actually, to completely capture all options, I found that WebFlakeStudio's solution is the best, with the following addition, to capture all 3 forms of *cough*client stupidity*cough*

    (PHP)

    preg_match('#(\.be/|/embed/|/v/|/watch\?v=)([A-Za-z0-9_-]{5,11})#', $YoutubeCode, $matches);
    if(isset($matches[2]) && $matches[2] != ''){
         $YoutubeCode = $matches[2];
    }
    

    I added the /embed, this should capture all. The Object, the URL and the Embed-option.

    0 讨论(0)
  • 2020-11-27 07:15

    I might get scolded for using a regex to parse html but given the circumstances maybe it's the best way to do it?

    preg_match('~/v/([0-9a-z_]+)~i', $code, $matches);
    echo $matches[1];
    

    assuming the valid characters for a youtube video id are 0-9a-z_

    0 讨论(0)
  • 2020-11-27 07:24

    There are generally two formats for YouTube video urls:

    http://www.youtube.com/v/[videoid]
    http://www.youtube.com/watch?v=[videoid]
    

    The "www.youtube.com" can be replaced by "www.youtube.co.uk", or other country codes, but as far as I've been able to determine, the video ids are the same regardless of the domain name.

    The video id is an 11-character string that uses base-64 encoding.

    Assuming you have code that will parse urls from an HTML document, you can determine if it's a YouTube video url and get the video id by using this regex (written in C#, but should be easily converted to php or anything else):

    "^http://(?<domain>([^./]+\\.)*youtube\\.com)(/v/|/watch\\?v=)(?<videoId>[A-Za-z0-9_-]{11})"
    

    This particular regex is specific to youtube.com. Making it understand all the different country codes (youtube.co.uk, youtube.pl, youtube.it, etc.) is somewhat more involved.

    0 讨论(0)
  • 2020-11-27 07:34

    If you want to get embed link for youtube video, you can use the following code snippet:

    $youtubeRegexp = "#(/v/|/watch\?v=)([A-Za-z0-9_-]{5,11})#";
    $embedUrl = preg_replace($youtubeRegexp, '/embed/$2', $videoUrl);
    

    For the current moment embed code is:

    <iframe width="{width}" height="{height}" src="{embed_url}" frameborder="0" allowfullscreen></iframe>
    

    Note: $videoUrl should be set to the original url prior to running this expression.

    0 讨论(0)
提交回复
热议问题