Get YouTube video ID using inline iframe code

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

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

I want to take the identifier 0gugBiEkLwU

Can anyone tell me how to do this. In fact, you need your help.

+3
source share
4 answers

Using this template with a capture group should give you the line you need:

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

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

+6
source

You can use:

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

Check out the demo here.

Explanation:

enter image description here

+4
source

, , - , . Youtube iframe src "? rel=" , :

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

- "/embed/" " /". , , .

: https://regex101.com/r/eW7rC1/1

+2

youtube URL- YouTube,

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);
0

All Articles