Friday 24 May 2013

Automatically hyperlink URL and Email in ASP.NET Pages with C#


Automatically hyperlink URL and Email in ASP.NET Pages with C#

Sample Image - Autohyperlink.jpg

Introduction

When I designed the web site http://www.outsourcexp.com/ , I found that many users post URL and Email information, but these URLs and Emails just display as text, if you want to visit these URLs or Emails ,you have to copy them then paste to your browser or outlook. I searched articles about Automatically hyperlink URLs but only found VB source code. so I decide do it myself.
The first step is how to detect URL and Email, of cause the best way is regular expressions. By using regular expressions, you can automatically detect hyperlink-sensitive text and automatically wrap them into element pointing to the same URL. Let's see how to proceed. The idea is preprocessing any displayable text using ad hoc regular expressions to identify portions of text that are email addresses or Web site URLs.
You create a RegEx object and initialize it with the regular expression. Next, you call IsMatch on the input string to see whether at least one match is found. Next, you call the method Replace. Replace takes the input as its first argument.
First, when you use regular expressions,you must include System.Text.RegularExpressions,
 using System.Text.RegularExpressions;

The second step is how to detect a URL,
Regex urlregex = new Regex(@"(http:\/\/([\w.]+\/?)\S*)",
                 RegexOptions.IgnoreCase|RegexOptions.Compiled);
Here is how to detect a Email,
Regex emailregex = new Regex(@"([a-zA-Z_0-9.-]+\@[a-zA-Z_0-9.-]+\.\w+)",
                   RegexOptions.IgnoreCase|RegexOptions.Compiled);
When you detected a URL or Email, you need to replace it with <a href=...></a> ,I put all these into a function,
private void Button1_Click(object sender, System.EventArgs e)
{
    string strContent = InputTextBox.Text;
    Regex urlregex = new Regex(@"(http:\/\/([\w.]+\/?)\S*)",
                     RegexOptions.IgnoreCase| RegexOptions.Compiled);
    strContent = urlregex.Replace(strContent, 
                 "<a href=\"$1\" target=\"_blank\">$1</a>");
    Regex emailregex = new Regex(@"([a-zA-Z_0-9.-]+\@[a-zA-Z_0-9.-]+\.\w+)",
                       RegexOptions.IgnoreCase| RegexOptions.Compiled);
    strContent = emailregex.Replace(strContent, "<a href=mailto:$1>$1</a>");
    lbContent.Text += "<br>"+strContent;
}

Here your go... Build this control library, add reference to your project and enjoy validating.

1 comment:

  1. All the post of this blog having the various topic of programming functionality.It should be more helpful to the people who are in the beginning stage of programming.
    Web Design Companies | Web Designing Companies

    ReplyDelete