Hassan Sardar
Hassan Sardar

Reputation: 4523

Find youtube Link in PHP string and Convert it into embed code?

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

Upvotes: 28

Views: 64890

Answers (14)

Suraj Dott
Suraj Dott

Reputation: 119

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;

Upvotes: 9

pgrono
pgrono

Reputation: 798

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;

Upvotes: 0

Syone
Syone

Reputation: 770

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

Upvotes: 33

Leffa
Leffa

Reputation: 504

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

Upvotes: 0

Nurul Huda
Nurul Huda

Reputation: 1593

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",
]

Upvotes: 1

Ahmad Mobaraki
Ahmad Mobaraki

Reputation: 8188

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!

Upvotes: 45

Sagive
Sagive

Reputation: 1837

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] ;
}

Upvotes: 3

Shakil Hossain
Shakil Hossain

Reputation: 1743

<?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> 

Upvotes: 1

iniravpatel
iniravpatel

Reputation: 1663

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;
}

Upvotes: 16

Mahesh Yadav
Mahesh Yadav

Reputation: 2684

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];

Upvotes: 1

Luke Stevenson
Luke Stevenson

Reputation: 10351

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!

Upvotes: 3

Michael Giovanni Pumo
Michael Giovanni Pumo

Reputation: 14794

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.

Upvotes: 0

Joran Den Houting
Joran Den Houting

Reputation: 3163

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']);

Upvotes: 44

Tim Nikischin
Tim Nikischin

Reputation: 855

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

Upvotes: 0

Related Questions