Suggestions & Issues

Better regex for get_video_id function

Today i was trying to show this video https://www.youtube.com/embed/JaNH56Vpg-A or https://www.youtube.com/embed/JaNH56Vpg-A

and both URLs wasn't working. So i've made a fix for that and this is the code:

function get_video_id($url)
{
// Handles normal youtube url e.g:
// http://www.youtube.com/watch?v=QRS8MkLhQmM
$regex1 = '#v=([^\s]{0,11})#is';

// Handles youtube share short links e.g:
// http://youtu.be/QRS8MkLhQmM
$regex2 = '#.*youtu\.be\/([^\s]{0,11})#is';

// Handles embedded youtube video url e.g:
// http://www.youtube.com/v/QRS8MkLhQmM?version=3&feature=player_embedded&autohide=1
// http://www.youtube.com/embed/QRS8MkLhQmM?version=3&feature=player_embedded&autohide=1
$regex3 = '#(?<=[v|embed])\/[v|embed]+\/([^\s]{0,11})#is';

// Handles videos IDs e.g:
// QRS8MkLhQmM
$regex4 = '#([^\s]{0,11})#is';
if ( preg_match($regex1, $url, $matches)
|| preg_match($regex2, $url, $matches)
|| preg_match($regex3, $url, $matches)
|| preg_match($regex4, $url, $matches) ) {
return $matches[1];
}

return 'QRS8MkLhQmM'; // default video ID on error
}

5 votes
Vote
Sign in
Check!
(thinking…)
Reset
or sign in with
  • facebook
  • google
    Password icon
    I agree to the terms of service
    Signed in as (Sign out)
    You have left! (?) (thinking…)
    Alysson BortoliAlysson Bortoli shared this idea  ·   ·  Admin →

    1 comment

    Sign in
    Check!
    (thinking…)
    Reset
    or sign in with
    • facebook
    • google
      Password icon
      I agree to the terms of service
      Signed in as (Sign out)
      Submitting...
      • Hi Alysson, thanks for reporting your issues!!

        I've already improved that function for version 1.9 so that it recognises the following "new" URLs:

        - Support for Youtube SSL URLs: https://
        - Support for Youtube embed URLs: http://www.youtube.com/v/VIDEO_ID and http://www.youtube.com/embed/VIDEO_ID

        Until I release version 1.9 I'll leave here the new code for the function get_video_id so you can use it today:

        function get_video_id($url)
        {
        if (preg_match('#^https?\://(?:(?:[a-z0-9-_\.]+\.|)youtube\.com/(?:watch\?v=|v/|embed/)|youtu\.be/)([a-z0-9-_]+)|^([a-z0-9-_]+)$#i', $url, $matches) > 0) {
        return $matches[empty($matches[1]) ? 2 : 1];
        }
        // default video ID on error
        return 'QRS8MkLhQmM';
        }

        It passes all unit tests.

        Cheers!

      Feedback and Knowledge Base