tags:

views:

47

answers:

2

For some reason I can't find this through searches, not really sure what keywords to use. In my web app, users enter text into plain text boxes. I want to automatically convert any http://somekind.oflink.com to an html anchor tag for them.

What's the best way to capture the link? I only want to support links that start with "http://".

Thanks!

A: 

Use a regular expression. You can find lost of expressions here: http://regexlib.com/Search.aspx?k=url

And then do something like this:

Regex regex = new Regex("YOUR PATTERN");
regex.Replace(
   textBlock, 
   delegate (Match m) { 
       return string.Format(@"<a href=""{0}"">{0}</a>", m.Groups[0]); 
   });

Note that you should replace "YOUR PATTERN" with the regular expression that fits your needs.

Martin Ingvar Kofoed Jensen
+3  A: 

Replace "(http://([^ ]+))" with "<a href=\"$1\">$2</a>"

  string input = "Why don't you use http://www.google.com for that?";
  string pattern = "(http://([^ ]+))";
  string replacement = "<a href=\"$1\">$2</a>";
  Regex rgx = new Regex(pattern);
  string result = rgx.Replace(input, replacement);
  Console.WriteLine("Original String: {0}", input);
  Console.WriteLine("Replacement String: {0}", result)
Amarghosh
Thanks for that, works great.
Chad