Click here to Skip to main content
13,095,921 members (53,930 online)
Click here to Skip to main content
Add your own
alternative version

Stats

71.3K views
507 downloads
26 bookmarked
Posted 28 Dec 2006

How to Make Dynamic Hyperlinks Using C# in ASP.NET

, 28 Dec 2006
Rate this:
Please Sign up or sign in to vote.
We've all seen blogs and other web sites that seem to be able to intersperse hyperlinks throughout their content, almost whimsically, if the given text is "linkable", or, formatted like a domain name or link of some kind. Here's how.

Introduction

We've all seen blogs and other web sites that seem to be able to intersperse hyperlinks throughout their content, almost whimsically, if the given text is "linkable", or, formatted like a domain name or link of some kind.

I recently had the need to do this (for my site, nonsequiturs.com), and couldn't find a great source for a starting point, well, in C# anyway. So, I went ahead and made one using regular expressions and simple string replaces. It works well, and is relatively fast and reliable. I thought I'd share the code in case others had the need for this functionality.

Features: Automatically makes a hyperlink out of anything that appears to be a domain name or URL. Will skip confusing text, like number sequences (e.g., 10.35), and will ignore existing hyperlinks. You can enclose text with a special tag if you want to specify an area that should not be processed (see the code comments for more). You can also add paramaters to the hyperlink tags that are generated, like "target=" and so forth.

For more code samples, or to contact me directly, visit my site.

/// <span class="code-SummaryComment"><summary></span>
/// Convert domain names and url paths to real web links.
/// Handles the most common web transport protocols.
/// Existing <span class="code-SummaryComment"><a> tag contents are ignored. Any valid urls</span>
/// within a <span class="code-SummaryComment"><nolink></nolink> tag are ignored.</span>
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="strvar">String to process.</param></span>
/// <span class="code-SummaryComment"><param name="param">String of parameters to insert into</span>
/// the resultant <span class="code-SummaryComment"><a> tags, like target="_blank".</param></span>
/// <span class="code-SummaryComment"><returns>A string with links</returns></span>
public static string AutoHyperlinks(string strvar, string param)
{
    // (c)2006 Michael Argentini, http://www.nonsequiturs.com.
    //
    // Please keep this copyright intact.
    // You may use or modify this code however you see fit,
    // within the scope of application or web site functionality.
    // Distribution of this code as an example or snippet is
    // prohibited. In this case, please link to the code example
    // on the nonsequiturs.com site directly!

    
    // First, process all <nolink> areas and change period
    // characters temporarily to avoid auto-hyperlink processing.
    string final = strvar;

    Regex regex = new Regex(@"<nolink>(.*?)</nolink>", 
                  RegexOptions.IgnoreCase | RegexOptions.Singleline | 
                  RegexOptions.CultureInvariant | 
                  RegexOptions.IgnorePatternWhitespace | 
                  RegexOptions.Compiled);
    
    MatchCollection theMatches = regex.Matches(strvar);
    
    for (int index = 0; index < theMatches.Count; index++)
    {
        final = final.Replace(theMatches[index].ToString(), 
                theMatches[index].ToString().Replace(".", "[[[pk:period]]]"));
    }

    // Second, process all existing <a> tags and change period
    // characters in them temporarily to avoid auto-hyperlink processing.
    regex = new Regex(@"<a(.*?)</a>", RegexOptions.IgnoreCase | 
            RegexOptions.Singleline | RegexOptions.CultureInvariant | 
            RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
    
    theMatches = regex.Matches(final);
    
    for (int index = 0; index < theMatches.Count; index++)
    {
        final = final.Replace(theMatches[index].ToString(), 
                theMatches[index].ToString().Replace(".", "[[[pk:period]]]"));
    }

    // Third, temporarily alter any digit sequences
    // that are formatted like domain names.
    final = Regex.Replace(final, @"(?<=\d)\.(?=\d)", "[[[pk:period]]]");
    
    // Fourth, look for, and process, any linkable domain names or URLs.
    Regex tags = new Regex(@"([a-zA-Z0-9\:/\-]*[a-zA-Z0-9\-_]\" + 
                 @".[a-zA-Z0-9\-_][a-zA-Z0-9\-_][a-zA-Z0-9\?\" + 
                 @"=&#_\-/\.]*[^<>,;\.\s\)\(\]\[\""])");

    // Fifth, fix any inadvertently altered protocol strings.
    final = tags.Replace(final, "<a href=\"http://$&\"" + 
                         param + ">$&</a>");
    final = final.Replace("http://https://", "https://");
    final = final.Replace("http://http://", "http://");
    final = final.Replace("http://ftp://", "ftp://");
    final = final.Replace("http://rtsp://", "rtsp://");
    final = final.Replace("http://mms://", "mms://");
    final = final.Replace("http://pcast://", "pcast://");
    final = final.Replace("http://sftp://", "sftp://");

    final = final.Replace("[[[pk:period]]]", ".");
    final = final.Replace("<nolink>", "");
    final = final.Replace("</nolink>", "");

    // Lastly, return the processed string.
    return final;
}<PRE>

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Argentini
Web Developer
United States United States
Michael Argentini is a part-time cryptozoologist who is best known for his theories concerning the existence of big foot, as well as impersonating big foot on several occasions as a prelude to intercourse.

You may also be interested in...

Pro
Pro

Comments and Discussions

 
QuestionNeed for help! [modified] Pin
tangcheehong25-Jun-09 22:18
membertangcheehong25-Jun-09 22:18 
NewsUPDATED VERSION OF THE FUNCTION Pin
pocketkaos29-Dec-06 9:59
memberpocketkaos29-Dec-06 9:59 
AnswerRe: UPDATED VERSION OF THE FUNCTION Pin
pocketkaos30-Dec-06 2:28
memberpocketkaos30-Dec-06 2:28 
Questionnice, but what about email links? Pin
Fred_Smith28-Dec-06 6:14
memberFred_Smith28-Dec-06 6:14 
AnswerRe: nice, but what about email links? Pin
pocketkaos28-Dec-06 9:45
memberpocketkaos28-Dec-06 9:45 
AnswerRe: nice, but what about email links? Pin
pocketkaos28-Dec-06 10:16
memberpocketkaos28-Dec-06 10:16 
GeneralRe: nice, but what about email links? Pin
Fred_Smith28-Dec-06 11:33
memberFred_Smith28-Dec-06 11:33 
GeneralRe: nice, but what about email links? Pin
Fred_Smith29-Dec-06 0:43
memberFred_Smith29-Dec-06 0:43 
GeneralRe: nice, but what about email links? Pin
pocketkaos29-Dec-06 3:08
memberpocketkaos29-Dec-06 3:08 
GeneralRe: nice, but what about email links? Pin
Fred_Smith29-Dec-06 3:18
memberFred_Smith29-Dec-06 3:18 
GeneralRe: nice, but what about email links? Pin
pocketkaos29-Dec-06 3:38
memberpocketkaos29-Dec-06 3:38 
GeneralRe: nice, but what about email links? Pin
Fred_Smith29-Dec-06 3:46
memberFred_Smith29-Dec-06 3:46 
GeneralRe: nice, but what about email links? Pin
pocketkaos29-Dec-06 3:53
memberpocketkaos29-Dec-06 3:53 
GeneralRe: nice, but what about email links? Pin
sn10225-Sep-07 5:31
membersn10225-Sep-07 5:31 
GeneralRe: nice, but what about email links? Pin
pocketkaos1-May-08 15:00
memberpocketkaos1-May-08 15:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.170813.1 | Last Updated 28 Dec 2006
Article Copyright 2006 by Argentini
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid