Vimeo YouTube Video ID from Embed Code or RegEx Regex URL

I want to get a video id for YouTube or Vimeo through its Embed code or URL, any solution for this with PHP?

+8
php regex youtube vimeo
source share
3 answers

You can use preg_match to get identifiers. I will talk about the expressions themselves later in this answer, but here is the basic idea of ​​using preg_match:

preg_match('expression(video_id)', "http://www.your.url.here", $matches); $video_id = $matches[1]; 

Here is a breakdown of the expressions for each type of possible input that you requested. I have included a link for each showing some test cases and results.

  • For YouTube URLs such as http://www.youtube.com/watch?v=89OpN_277yY , you can use this expression:

     v=(.{11}) 
  • YouTube embed codes may look like this (some extraneous things are cropped):

     <object width="640" height="390"> <param name="movie" value="http://www.youtube.com/v/89OpN_277yY?fs=... ... </object> 

    Or like this:

     <iframe ... src="http://www.youtube.com/embed/89OpN_277yY" ... </iframe> 

    Thus, the expression to get the identifier from any style will be this :

     \/v\/(.{11})|\/embed\/(.{11}) 
  • Vimeo urls look like http://vimeo.com/<integer> as far as I can tell. The lowest I found was just http://vimeo.com/2 , and I don’t know if there is an upper limit, but at the moment I assume it is limited to 10 digits. Hope someone can fix me if they know the details. This expression can be used:

     vimeo\.com\/([0-9]{1,10}) 
  • Vimeo embed code takes this form:

     <iframe src="http://player.vimeo.com/video/<integer>" width="400" ... 

    So you can use this expression:

     player\.vimeo\.com\/video\/([0-9]{1,10}) 

    Otherwise, if the length of the numbers can eventually exceed 10, you can use:

     player\.vimeo\.com\/video/([0-9]*)" 

    Keep in mind that " will need to be escaped with \ if you enclose the expression in double quotes.


In the resume , I'm not sure how you wanted to implement this, but you could either combine all the expressions with | , or you could match them separately. Add a comment to this answer if you want me to provide additional information on how to combine expressions.

+19
source share

Here is another similar one [for youtube only], it may be useful to look. PHP regex to get youtube video id?

+2
source share

According to the latest youtube standard, you can use the following code to extract the video id from the embed code.

 $embed = '<iframe src="//www.youtube.com/embed/n6WYu-pSXH8" frameborder="0"></iframe>'; preg_match('~embed/(.*?)"~', $embed, $output); echo $output[1]; 

thanks

0
source share

All Articles