开发者

Using C#, how to search and enter a hyperlink in a block of text?

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://".开发者_如何学Python

Thanks!


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜