Switch URL to Youtube video, Switch URL to Hyperlink using c#

Saturday, July 02, 2011 9:18 PM | Leave a reply »

a friend of mine (who is not a developer) has told me that facebook is somehow affiliated with youtube and his reason was that if you type a video URL in the post box in facebook it automatically appears as video

it took me 10 minutes to build this demo,

this demo takes a block of text “post text ” which presumably includes a youtube URL and turns it into a youtube video in a webpage

 

   1: private const string FIND_URL_REGEX = "http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?";
   2: private const string YOUTUBE_TEMPLATE = "<object width=\"425\" height=\"355\"><param name=\"movie\" value=\"http://www.youtube.com/v/{0}&amp;hl=en\"><embed src=\"http://www.youtube.com/v/{0}&amp;hl=en\" type=\"application/x-shockwave-flash\" width=\"425\" height=\"355\"></object>";
   3: private const string URL_TEMPLATE = "<a href=\"{0}\">{0}</a>";
   4:  
   5:  
   6: protected string MakeLinks(string txt)
   7: {
   8:     Regex regx = new Regex(FIND_URL_REGEX, RegexOptions.IgnoreCase);
   9:     MatchCollection mactches = regx.Matches(txt);
  10:     foreach (Match match in mactches)
  11:     {
  12:         if (match.Value.ToLower().Contains("youtube.com"))
  13:         {
  14:             try
  15:             {
  16:                 txt = txt.Replace(match.Value, string.Format(YOUTUBE_TEMPLATE, match.Value.Split('=')[1].Split('&')[0]));
  17:             }
  18:             catch { }
  19:         }
  20:         else
  21:         {
  22:             txt = txt.Replace(match.Value, string.Format(URL_TEMPLATE, match.Value));
  23:         }
  24:     }
  25:     return txt;
  26: }
  27:  
  28:  

the previous code takes a block of text assuming this is what the user has posted and switches and text that looks like a URL to a hyper link and any youtube URL to video block



Comments

No comments posted yet.

Leave a Reply



 

Please add 7 and 5 and type the answer here: