28

Find a Youtube video link in PHP String and convert it into Embed Code?

Embed Code:

<iframe width="420" height="315" src="//www.youtube.com/embed/0GfCP5CWHO0" frameborder="0" allowfullscreen></iframe>

PHP Code / String:

<?php echo $post_details['description']; ?>

Youtube Link:

http://www.youtube.com/watch?v=0GfCP5CWHO0
4

14 Answers 14

46

There are two types of youtube link for one video:

Example:

$link1 = 'https://www.youtube.com/watch?v=NVcpJZJ60Ao';
$link2 = 'https://www.youtu.be/NVcpJZJ60Ao';

This function handles both:

function getYoutubeEmbedUrl($url)
{
     $shortUrlRegex = '/youtu.be\/([a-zA-Z0-9_-]+)\??/i';
     $longUrlRegex = '/youtube.com\/((?:embed)|(?:watch))((?:\?v\=)|(?:\/))([a-zA-Z0-9_-]+)/i';

    if (preg_match($longUrlRegex, $url, $matches)) {
        $youtube_id = $matches[count($matches) - 1];
    }

    if (preg_match($shortUrlRegex, $url, $matches)) {
        $youtube_id = $matches[count($matches) - 1];
    }
    return 'https://www.youtube.com/embed/' . $youtube_id ;
}

The output of $link1 or $link2 would be the same :

 $output1 = getYoutubeEmbedUrl($link1);
 $output2 = getYoutubeEmbedUrl($link2);
 // output for both:  https://www.youtube.com/embed/NVcpJZJ60Ao

Now you can use the output in iframe!

Sign up to request clarification or add additional context in comments.

3 Comments

What happens in situations where the url will be like so: https://www.youtube.com/watch?time_continue=1&v=NVcpJZJ60Ao ?
I added a hyphen to this to make it work with some of my share links: $shortUrlRegex = '/youtu.be\/([a-zA-Z0-9_-]+)\??/i';
This should be the accepted answer, it helped me greatly, thank you!
44

Try this:

preg_replace("/\s*[a-zA-Z\/\/:\.]*youtube.com\/watch\?v=([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i","<iframe width=\"420\" height=\"315\" src=\"//www.youtube.com/embed/$1\" frameborder=\"0\" allowfullscreen></iframe>",$post_details['description']);

8 Comments

Rest of the code is working perfect , but if i post : "Check this video : youtube.com/watch?v=0GfCP5CWHO0 " . video does appears but the text appears with too many spaces
Can you give an example of the output? Please update your openings post :)
here is the out put ,, check the words on top of the video: img585.imageshack.us/img585/1025/vfxy.png
It's a styling issue, nothing to to with my code! You can use the above and just need to style the text. :)
But styling are totally perfect without this code, if i press enter and than place the youtube link , it works fine, but for the single link it appears link this
|
33

A little enhancement of Joran's solution to handle all these use cases:

Long URL: https://www.youtube.com/watch?v=[ID]
    
Short URL: https://youtu.be/[ID]

Long URL with time parameter: https://www.youtube.com/watch?v=[ID]&t=[TIME]s

Short URL with time parameter: https://youtu.be/[ID]?t=[TIME]

Long URL with other parameters: https://www.youtube.com/watch?v=[ID]&t=[TIME]s&foo=hello&bar=world

Short URL with other parameters: https://youtu.be/[ID]?t=[TIME]&foo=hello&bar=world

Mobile URL: https://m.youtube.com/watch?v=[ID]&t=[TIME]s
function convertYoutube($string) {
    return preg_replace(
        "/[a-zA-Z\/\/:\.]*youtu(?:be.com\/watch\?v=|.be\/)([a-zA-Z0-9\-_]+)(?:[&?\/]t=)?(\d*)(?:[a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i",
        "<iframe width=\"420\" height=\"315\" src=\"https://www.youtube.com/embed/$1?start=$2\" allowfullscreen></iframe>",
        $string
    );
}

You can test this function online here

3 Comments

However the code is working but it displays only a small video
You can set the width and height you want to the iframe : syframework.alwaysdata.net/convert-youtube-url-to-iframe
this does not work. change anything in the text string and hit run. iframe scr has no "v" value anymore.
16

A quick function for generating Embed url link of any of the FB/vimeo/youtube videos.

public function generateVideoEmbedUrl($url){
    //This is a general function for generating an embed link of an FB/Vimeo/Youtube Video.
    $finalUrl = '';
    if(strpos($url, 'facebook.com/') !== false) {
        //it is FB video
        $finalUrl.='https://www.facebook.com/plugins/video.php?href='.rawurlencode($url).'&show_text=1&width=200';
    }else if(strpos($url, 'vimeo.com/') !== false) {
        //it is Vimeo video
        $videoId = explode("vimeo.com/",$url)[1];
        if(strpos($videoId, '&') !== false){
            $videoId = explode("&",$videoId)[0];
        }
        $finalUrl.='https://player.vimeo.com/video/'.$videoId;
    }else if(strpos($url, 'youtube.com/') !== false) {
        //it is Youtube video
        $videoId = explode("v=",$url)[1];
        if(strpos($videoId, '&') !== false){
            $videoId = explode("&",$videoId)[0];
        }
        $finalUrl.='https://www.youtube.com/embed/'.$videoId;
    }else if(strpos($url, 'youtu.be/') !== false){
        //it is Youtube video
        $videoId = explode("youtu.be/",$url)[1];
        if(strpos($videoId, '&') !== false){
            $videoId = explode("&",$videoId)[0];
        }
        $finalUrl.='https://www.youtube.com/embed/'.$videoId;
    }else{
        //Enter valid video URL
    }
    return $finalUrl;
}

Comments

9

Example:

$link1 = getEmbedUrl('https://www.youtube.com/watch?v=BIjqw7zuEVE');
$link2 = getEmbedUrl('https://vimeo.com/356810502');
$link3 = getEmbedUrl('https://example.com/link/12345');

Function:

function getEmbedUrl($url) {
    // function for generating an embed link
    $finalUrl = '';

    if (strpos($url, 'facebook.com/') !== false) {
        // Facebook Video
        $finalUrl.='https://www.facebook.com/plugins/video.php?href='.rawurlencode($url).'&show_text=1&width=200';

    } else if(strpos($url, 'vimeo.com/') !== false) {
        // Vimeo video
        $videoId = isset(explode("vimeo.com/",$url)[1]) ? explode("vimeo.com/",$url)[1] : null;
        if (strpos($videoId, '&') !== false){
            $videoId = explode("&",$videoId)[0];
        }
        $finalUrl.='https://player.vimeo.com/video/'.$videoId;

    } else if (strpos($url, 'youtube.com/') !== false) {
        // Youtube video
        $videoId = isset(explode("v=",$url)[1]) ? explode("v=",$url)[1] : null;
        if (strpos($videoId, '&') !== false){
            $videoId = explode("&",$videoId)[0];
        }
        $finalUrl.='https://www.youtube.com/embed/'.$videoId;

    } else if(strpos($url, 'youtu.be/') !== false) {
        // Youtube  video
        $videoId = isset(explode("youtu.be/",$url)[1]) ? explode("youtu.be/",$url)[1] : null;
        if (strpos($videoId, '&') !== false) {
            $videoId = explode("&",$videoId)[0];
        }
        $finalUrl.='https://www.youtube.com/embed/'.$videoId;

    } else if (strpos($url, 'dailymotion.com/') !== false) {
        // Dailymotion Video
        $videoId = isset(explode("dailymotion.com/",$url)[1]) ? explode("dailymotion.com/",$url)[1] : null;
        if (strpos($videoId, '&') !== false) {
            $videoId = explode("&",$videoId)[0];
        }
        $finalUrl.='https://www.dailymotion.com/embed/'.$videoId;

    } else{
        $finalUrl.=$url;
    }

    return $finalUrl;
}

Updated Link for Dailymotion:

$finalUrl .= 'https://geo.dailymotion.com/player.html?video='.$videoId;

1 Comment

Hi Suraj, am wondering how to use this to generate the thumbnails for each video? Is that possible?
3

I know this is an old thread, but for anyone having this challenge and looking for assistance, I found a PHP Class on GitHub - Embera.

Basically an oembed library which converts YouTube URLs in any string into the associated iframe element. I'm using it, and will continue to use it everywhere!

Comments

3

I think a safe, super simple way to get the id
which is kinda bulletproof is to simply use the URL structure.

function getYoutubeEmbedUrl($url){

    $urlParts   = explode('/', $url);
    $vidid      = explode( '&', str_replace('watch?v=', '', end($urlParts) ) );

    return 'https://www.youtube.com/embed/' . $vidid[0] ;
}

Comments

1

Below will work for all type of YouTube URLs.

preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);

$youtube_id = $match[1];

Comments

1
<?php
$url = 'https://www.youtube.com/watch?v=u9-kU7gfuFA';
preg_match('/[\\?\\&]v=([^\\?\\&]+)/', $url, $matches);
$id = $matches[1];
$width = '800px';
$height = '450px'; ?>

<iframe id="ytplayer" type="text/html" width="<?php echo $width ?>" height="<?php echo $height ?>"
src="https://www.youtube.com/embed/<?php echo $id ?>?rel=0&showinfo=0&color=white&iv_load_policy=3"
frameborder="0" allowfullscreen></iframe> 

Comments

1

Another simple alternative would be using parse_url and parse_str functions.

function getYoutubeEmbedUrl ($url) {
  $parsedUrl = parse_url($url);
  # extract query string
  parse_str(@$parsedUrl['query'], $queryString);
  $youtubeId = @$queryString['v'] ?? substr(@$parsedUrl['path'], 1);

  return "https://youtube.com/embed/{$youtubeId}";
}

Lets say we have these two links:

$link1 = 'https://www.youtube.com/watch?v=NVcpJZJ60Ao';
$link2 = 'https://www.youtu.be/NVcpJZJ60Ao';

getYoutubeEmbedUrl($link1); // https://youtube.com/embed/NVcpJZJ60Ao
getYoutubeEmbedUrl($link2); // https://youtube.com/embed/NVcpJZJ60Ao

Explanation

parse_url function will extract link into 4 components: scheme, host, path, and query (see docs).

parse_url($link1);

// output
[
  "scheme" => "https",
  "host" => "www.youtube.com",
  "path" => "/watch",
  "query" => "v=NVcpJZJ60Ao",
]

The output of $link2 would be:

parse_url($link2);

// output
[
  "scheme" => "https",
  "host" => "www.youtu.be",
  "path" => "/NVcpJZJ60Ao",
]

And parse_str will convert query string into an array (see docs).

parse_str('v=NVcpJZJ60Ao', $output);

// value of variable $output
[
  "v" => "NVcpJZJ60Ao",
]

Comments

0

Well, you need to filter out the youtube links first and put them into an array. Next you need to find out the video id of the url which is very easy. Use this script:

function getIDfromURL() {
var video_url = document.getElementById('url').value;
var video_id = video_url.split('v=')[1];
var ampersandPosition = video_id.indexOf('&');
if (ampersandPosition != -1) { video_id = video_id.substring(0, ampersandPosition); }
document.getElementById('url').value=video_id;
}

You can of course use a PHP function as well, but I just used JS here to get the id from the URL. Maybe that helped anyways ;)

With the video id you can embed the video ;)

Comments

0

If the string is from user input, or in any way unpredictable, then forget using RegEx...seriously. It will open a can of worms for you.

Instead, try to look into using a HTML parser to extract the URL's based on certain rules and selectors.

I mainly use ColdFsuion / Java and JSoup is amazing for this kind of thing, with a whole lot more ease and security too.

http://jsoup.org/

It seems, in PHP, you could use something like this:

http://code.google.com/p/phpquery/

I'd love to give a code sample, but I don't know PHP well enough. But give it a go.

Mikey.

1 Comment

would $purifier->purify(preg_replace("/\s*[a-zA-Z\/\/:\.]*youtube.com\/watch\?v=([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i","<iframe width=\"315\" height=\"210\" src=\"//www.youtube.com/embed/$1\" frameborder=\"0\" allowfullscreen></iframe>",$chat_info['text'])); be sufficient?
0

Try this too:

$text = "is here the text to replace"; 

 function replace_iframe($id_video) {
    return '<iframe height="315"  width="100%" src="https://www.youtube.com/embed/'.$id_video[1].'" frameborder="0" allowfullscreen></iframe>';
 }

echo preg_replace_callback("/\s*[a-zA-Z\/\/:\.]*(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i", 'replace_iframe', $text);

Comments

0
function convertYoutubeLinkToEmbed($text) {
    $pattern = '#https?://(?:www\.)?(?:youtube\.com/watch\?v=|youtu\.be/)([\w-]+)#i';
    $replacement = '<iframe width="560" height="315" src="https://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>';
    
    return preg_replace($pattern, $replacement, $text);
}


$text = 'Check this video: https://www.youtube.com/watch?v=0GfCP5CWHO0';
$embedText = convertYoutubeLinkToEmbed($text);

echo $embedText;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.