views:

45

answers:

2

If you have text coming from a database such as:

 "New Apple TV Offers 8 GB of Internal Storage, 256 MB RAM http://t.co/fQ7rquF"

Is there a helper method that takes that text and wraps the web address as a anchor tag?

+1  A: 

Off the top of my head I would run a regular expression to match a link pattern and throw the anchor tags around it.

Found this on google:

using System.Text.RegularExpressions; 

public string ConvertURLsToHyperlinks(string sInput) 
{ 
    return Regex.Replace(sInput, @"(\bhttp://[^ ]+\b)", @"<a href=""$0"">$0</a>"); 
}

It looks for "http://" followed by anything that's not a space, separated by word boundaries.

Kevin
This will work in the example stated in the question, but many URLs in the real world end in a slash (`/`) or other punctuation characters and your regex wouldn’t match that.
Timwi
This didnt work actually. I copied the RegEx from the link Kevin gave and that worked - Regex.Replace(sInput, @"(\bhttp://[^ ]+\b)", @"<a href=""$0"">$0</a>");
Jon
@Timwi - how can we modify the Regex to fix it?
Jon
Just make sure you don't convert URLs of the form `http://t.co/@"onmouseover=`
dtb
@Timwi - it seems fine with a slash on the end
Jon
@Jon: No, it doesn’t. It doesn’t linkify the slash. (And other punctuation characters.)
Timwi
Well spotted. How can we fix this?
Jon
adding the literal `"` to the `[^ ]` group should take care of that.
Kevin
+1  A: 

i believe there is no such helper method but u can create one

public static class helper{
public static string AnchorHelper(this htmlHelper helper, string text)
{
   //here u can use kevin's function to generate anchors
   return ConvertURLsToHyperlinks(text);  
}
}

you have to add corresponding namespace in ur view and then u can just use it like other html helpers

<%=Html.AnchorHelper(TextwithUrls)%>
Muhammad Adeel Zahid
The class needs to be marked `static` for extension methods to be permitted in it.
Timwi
@Timwi thanks for correction. updated the answer
Muhammad Adeel Zahid