5

I want to get the YouTube video ID from YouTube embed code using preg_match or regex. For a example

<iframe width="560" height="315" src="//www.youtube.com/embed/0gugBiEkLwU?rel=0" frameborder="0" allowfullscreen></iframe> 

I want to take the ID 0gugBiEkLwU

Can anyone tell me how to do this. Really appropriate your help.

zack
  • 484
  • 3
  • 9
  • 25
  • possible duplicate of [RegEx pattern to get the YouTube video ID from any YouTube URL](http://stackoverflow.com/questions/9594943/regex-pattern-to-get-the-youtube-video-id-from-any-youtube-url) – Rikesh Feb 18 '14 at 05:40
  • possible duplicate of [How to find all Youtube video ids in a string using a regex?](http://stackoverflow.com/questions/5830387/how-to-find-all-youtube-video-ids-in-a-string-using-a-regex) – HamZa Mar 19 '14 at 21:10

4 Answers4

7

Using this pattern with a capturing group should give you the string you want:

d\/(\w+)\?rel=\d+"

example: https://regex101.com/r/kH5kA7/1

l'L'l
  • 44,951
  • 10
  • 95
  • 146
4

You can use :

src="\/\/(?:https?:\/\/)?.*\/(.*?)\?rel=\d*"

Check Demo Here

Explanation :

enter image description here

Sujith PS
  • 4,776
  • 3
  • 34
  • 61
3

I know this is pretty late, but I came up with something for people who might still be looking. Since not all Youtube iframe src attributes end in "?rel=", and can sometimes end in another query string or end with a double quote, you can use:

/embed\/([\w+\-+]+)[\"\?]/

This captures anything after "/embed/" and before the ending double-quote/query string. The selection can include any letter, number, underscore and hyphen.

Here's a demo with multiple examples: https://regex101.com/r/eW7rC1/1

0

The below function will extract the youtube video id from the all format of youtube urls,

function getYoutubeVideoId($iframeCode) {
    
    // Extract video url from embed code
    return preg_replace_callback('/<iframe\s+.*?\s+src=(".*?").*?<\/iframe>/', function ($matches) {
        // Remove quotes
        $youtubeUrl = $matches[1];
        $youtubeUrl = trim($youtubeUrl, '"');
        $youtubeUrl = trim($youtubeUrl, "'");
        // Extract id
        preg_match("/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'>]+)/", $youtubeUrl, $videoId);
        return $youtubeVideoId = isset($videoId[1]) ? $videoId[1] : "";
    }, $iframeCode);
    
}

$iframeCode = '<iframe width="560" height="315" src="http://www.youtube.com/embed/0gugBiEkLwU?rel=0" frameborder="0" allowfullscreen></iframe>';

// Returns youtube video id
echo getYoutubeVideoId($iframeCode);
Nanda
  • 11
  • 3