Meh Man
Meh Man

Reputation: 473

convert string to html (hyperlink)

i defined ToHtml() extension for string class and convert break to <br/>. how can detect hyper link and convert to <a> element?

public static class StringExtension
{
    public static string ToHtml(this string item)
    {
        //\r\n windows
        //\n unix
        //\r mac os
        return item.Replace("\r\n", "<br/>").Replace("\n", "<br/>").Replace("\r", "<br/>");
    }
}

c#, asp.net

Upvotes: 3

Views: 11061

Answers (3)

CloudyMarble
CloudyMarble

Reputation: 37566

By using:

string strContent = YourText;
Regex urlregex = new Regex(@"(http:\/\/([\w.]+\/?)\S*)",
                 RegexOptions.IgnoreCase| RegexOptions.Compiled);
strContent = urlregex.Replace(strContent, 
             "<a href=\"$1\" target=\"_blank\">$1</a>");     

Upvotes: 1

AidanO
AidanO

Reputation: 878

You could use a regular expression here to identify where the hyperlink begins and ends (possibly based on the length of the match) Then add in your anchor tags before and after.

Upvotes: 1

robasta
robasta

Reputation: 4701

see this one, uses regex

private string ConvertUrlsToLinks(string msg) {
    string regex = @"((www\.|(http|https|ftp|news|file)+\:\/\/)[&#95;.a-z0-9-]+\.[a-z0-9\/&#95;:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
    Regex r = new Regex(regex, RegexOptions.IgnoreCase);
    return r.Replace(msg, "<a href=\"$1\" title=\"Click to open in a new window or tab\" target=\"&#95;blank\">$1</a>").Replace("href=\"www", "href=\"http://www");
}

Upvotes: 5

Related Questions