Find youtube Link in PHP string and Convert it into embed code?
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;
}
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!
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']);
A little enhancement of Joran's solution to handle also youtube short URL format:
function convertYoutube($string) {
return preg_replace(
"/\s*[a-zA-Z\/\/:\.]*youtu(be.com\/watch\?v=|.be\/)([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i",
"<iframe src=\"//www.youtube.com/embed/$2\" allowfullscreen></iframe>",
$string
);
}
You can test this function online here