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:
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
The IFrame player API lets you embed a YouTube video player on your website and control the player using JavaScript.
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>
// ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With