Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert string to html (hyperlink)

Tags:

c#

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

like image 209
Meh Man Avatar asked Nov 17 '25 05:11

Meh Man


2 Answers

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");
}
like image 98
robasta Avatar answered Nov 19 '25 22:11

robasta


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.

like image 30
AidanO Avatar answered Nov 19 '25 22:11

AidanO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!