Get Youtube Video ID from html code with PHP

后端 未结 5 1929
小蘑菇
小蘑菇 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: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://(?([^./]+\\.)*youtube\\.com)(/v/|/watch\\?v=)(?[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.

提交回复
热议问题