Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert youtube url to iframe embed code

Tags:

c#

regex

asp.net

I've been trying to find a regex pattern to replace all youtube URLs in a string with the iframe embed code (C#). Obviously the video ID has to extracted. Here is the url patterns that should match:

  • http://www.youtube.com/watch?v=bSiDLCf5u3s
  • https://www.youtube.com/watch?v=bSiDLCf5u3s
  • http://youtu.be/bSiDLCf5u3s
  • www.youtube.com/watch?v=bSiDLCf5u3s
  • youtu.be/bSiDLCf5u3s
  • http://www.youtube.com/watch?feature=player_embedded&v=bSiDLCf5u3s
  • www.youtube.com/watch?feature=player_embedded&v=bSiDLCf5u3s

all possible urls should be replaced with:

<iframe title='YouTube video player' width='480' height='390' src='http://www.youtube.com/embed/VIDEO_ID_EXTRACTED' frameborder='0' allowfullscreen='1'></iframe>

Can someone please point me to a right direction.

Thank you in advance

like image 264
ShyGuy82 Avatar asked Apr 05 '13 01:04

ShyGuy82


People also ask

Can YouTube videos can be embedded using an iframe?

The IFrame player API lets you embed a YouTube video player on your website and control the player using JavaScript.


1 Answers

Here is the regex:

(?:https?:\/\/)?(?:www\.)?(?:(?:(?:youtube.com\/watch\?[^?]*v=|youtu.be\/)([\w\-]+))(?:[^\s?]+)?)

Should match all the links you posted and extracts the video ID as $1. And with the following code you replace the links with the <iframe/>:

const string input = "http://www.youtube.com/watch?v=bSiDLCf5u3s " +
                     "https://www.youtube.com/watch?v=bSiDLCf5u3s " +
                     "http://youtu.be/bSiDLCf5u3s " +
                     "www.youtube.com/watch?v=bSiDLCf5u3s " +
                     "youtu.be/bSiDLCf5u3s " +
                     "http://www.youtube.com/watch?feature=player_embedded&v=bSiDLCf5u3s " +
                     "www.youtube.com/watch?feature=player_embedded&v=bSiDLCf5u3s " +
                     "http://www.youtube.com/watch?v=_-QpUDvTdNY";
const string pattern = @"(?:https?:\/\/)?(?:www\.)?(?:(?:(?:youtube.com\/watch\?[^?]*v=|youtu.be\/)([\w\-]+))(?:[^\s?]+)?)";
const string replacement = "<iframe title='YouTube video player' width='480' height='390' src='http://www.youtube.com/embed/$1' frameborder='0' allowfullscreen='1'></iframe>";

var rgx = new Regex(pattern);
var result = rgx.Replace(input, replacement);

// result ==
// <iframe title='YouTube video player' width='480' height='390' src='http://www.youtube.com/embed/bSiDLCf5u3s' frameborder='0' allowfullscreen='1'></iframe>
// ...
like image 141
Linus Caldwell Avatar answered Oct 05 '22 07:10

Linus Caldwell