c# - Convert youtube url to iframe embed code -
i've been trying find regex pattern replace youtube urls in string iframe embed code (c#). video id has extracted. here url patterns 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 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 please point me right direction.
thank in advance
here regex:
(?:https?:\/\/)?(?:www\.)?(?:(?:(?:youtube.com\/watch\?[^?]*v=|youtu.be\/)([\w\-]+))(?:[^\s?]+)?)
should match links posted , extracts video id $1
. , following code replace links <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> // ...
Comments
Post a Comment