65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 C# 在 ASP.NET 中创建动态超链接

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.10/5 (7投票s)

2006年12月28日

viewsIcon

89585

downloadIcon

532

我们都见过能够在内容中随意插入超链接的博客和其他网站,只要给定的文本是“可链接的”,或者格式像域名或某种链接即可。以下是如何实现的。

引言

我们都见过能够在内容中随意插入超链接的博客和其他网站,只要给定的文本是“可链接的”,或者格式像域名或某种链接即可。

我最近需要这样做(为我的网站 nonsequiturs.com),但找不到一个好的起点,至少在 C# 中找不到。因此,我使用正则表达式和简单的字符串替换编写了一个。它运行良好,相对快速可靠。我想分享这段代码,以防其他人需要此功能。

特性: 自动将任何看起来像域名或 URL 的内容转换为超链接。将跳过令人困惑的文本,例如数字序列(例如,10.35),并且将忽略现有的超链接。您可以将文本包含在特殊标记中,以指定不应处理的区域(有关更多信息,请参见代码注释)。您还可以向生成的超链接标记添加参数,例如 "target=" 等。

有关更多代码示例,或直接联系我,请访问 我的网站

/// <summary>

/// Convert domain names and url paths to real web links.

/// Handles the most common web transport protocols.

/// Existing <a> tag contents are ignored. Any valid urls

/// within a <nolink></nolink> tag are ignored.

/// </summary>

/// <param name="strvar">String to process.</param>

/// <param name="param">String of parameters to insert into

/// the resultant <a> tags, like target="_blank".</param>

/// <returns>A string with links</returns>

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;
}
© . All rights reserved.