C# Code to Linkify Urls in a String

C# code to linkify urls in a string

It's a pretty simple task you can acheive it with Regex and a ready-to-go regular expression from:

  • http://regexlib.com/

Something like:

var html = Regex.Replace(html, @"^(http|https|ftp)\://[a-zA-Z0-9\-\.]+" +
"\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?" +
"([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*$",
"<a href=\"$1\">$1</a>");

You may also be interested not only in creating links but in shortening URLs. Here is a good article on this subject:

  • Resolve and shorten URLs in C#

See also:

  • Regular Expression Workbench at MSDN
  • Converting a URL into a Link in C# Using Regular Expressions
  • Regex to find URL within text and make them as link
  • Regex.Replace Method at MSDN
  • The Problem With URLs by Jeff Atwood
  • Parsing URLs with Regular Expressions and the Regex Object
  • Format URLs in string to HTML Links in C#
  • Automatically hyperlink URL and Email in ASP.NET Pages with C#

Linkify URLs in string with Regex expression

Anton Hansson gave you link to valid regex and replacement code. Below is more advaced way if you wan't to do something more with found urls etc.

var regex = new Regex("some valid regex");
var text = "your original text to linkify";
MatchEvaluator evaluator = LinkifyUrls;
text = regex.Replace(text, evaluator);

...

private static string LinkifyUrls(Match m)
{
return "<a href=\"" + m.Value + "\">" + m.Value + "</a>";
}

Easiest way to convert a URL to a hyperlink in a C# string?

Regular expressions are probably your friend for this kind of task:

Regex r = new Regex(@"(https?://[^\s]+)");
myString = r.Replace(myString, "<a href=\"$1\">$1</a>");

The regular expression for matching URLs might need a bit of work.

Regular expression to find URLs within a string

I am using this right now:

text = Regex.Replace(text,
@"((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)",
"<a target='_blank' href='$1'>$1</a>");

Asp.net C# Replacing all the urls of a string with an a href link

In a sample I used this markup

<body>
<form id="form1" runat="server">
<div>
<asp:Literal ID="litTextWithLinks" runat="server" />
</div>
</form>
</body>

along with that code-behind

private const string INPUT_STRING = "Bla bla bla bla http://www.site.com and bla bla http://site2.com blabla";

protected void Page_Load ( object sender, EventArgs e ) {
var outputString = INPUT_STRING;

Regex regx = new Regex( @"https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?", RegexOptions.IgnoreCase );

MatchCollection mactches = regx.Matches( INPUT_STRING );
foreach ( Match match in mactches ) {
outputString = outputString.Replace( match.Value, String.Format( "<a href=\"{0}\" target=\"_blank\">{0}</a>", match.Value ) );
}

litTextWithLinks.Text = outputString;
}

For all URLs from your sample where correctly replaced with links that opened in a new browser window.

You could test the url by doing a WebRequest and only replacing if opening succeeds. If not all URLs match, then you probably need to change the regular expression.

If this doesn't answer your question, you should add some more detail.

How can I add a text (https://) to a string that does not start with https:// but instead www?

A more elegant solution would be to use the UriBuilder class (which can also add a missing www.):

URLButton.Clicked += (object sender, EventArgs e) => {
Uri value = new UriBuilder(website.Text).Uri;
website.Text = value.AbsoluteUri;
Device.OpenUri(value);
}

jQuery + C# code to resolve URL's from user-supplied text

I ended up using server-side C# code to do the linkification. I use an AJAX-jQuery wrapper to call into a PageMethod that does the work.

The PageMethod both linkifies and sanitizes the user-supplied string, then returns the result.

I use the Microsoft Anti-Cross Site Scripting Library (AntiXSS) to sanitize:

http://www.microsoft.com/download/en/details.aspx?id=5242

And I use C# code I found here and there to resolve and shorten links using good olde string parsing and regular expressions.

My method is not as cool as the way FaceBook does it in real time, but at least now my users can add links to their descriptions and comments.

How to convert unclickable plain text URLs to links in HTML source

After changing project build target from 4.7.2 to 4.5 and go back to 4.7.2 again fixed the "bug".

Here is the working code:

var htmlVersion = "<html><head></head><body>\r\n"
+ "Some text\r\n"
+ "<div>http://google.com</div>\r\n"
+ " Then later more text: http://500px.com\r\n"
+ "<div>Sub <span>abc</span> Back text</div>\r\n"
+ "And the final text"
+ "</body></html>";

var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(htmlVersion);

// Linkify body
var modified = false;
var bodyNode = doc.DocumentNode.SelectSingleNode("//body");
var before = bodyNode.InnerHtml;
bodyNode = Linkify(bodyNode);
modified = modified || bodyNode.InnerHtml != before;

The recursive Linkify function:

HtmlAgilityPack.HtmlNode Linkify(HtmlAgilityPack.HtmlNode node)
{
if (node == null || node.Name == "a") // It's already a link
{
return node;
}

if (node.Name == "#text") // Do replacement here
{

// Create links
// https://stackoverflow.com/a/4750468/627193
node.InnerHtml = Regex.Replace(node.InnerHtml,
@"((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)",
"<a target='_blank' href='$1'>$1</a>");

}

for (int i = 0; i < node.ChildNodes.Count; i++) // Go for child nodes
{
node.ChildNodes[i] = Linkify(node.ChildNodes[i]);
}
return node;
}


Related Topics



Leave a reply



Submit