Home  »  Code Snippets  »  ASP.Net  »

Find URL in string and make it links

 Posted By : Manoranjan SahooPosted Date : 26/08/2011 06:40:29 AM Category : ASP.Net Points : 3

Sometimes we need to create dynamically all url into a html link. We can do this using RegularExpression to find URL and then make change that into link.

use below code to replace all url from a string into link.

code :

string strContent = "some text some text. http://google.com some text some text, http://aol.com some text dklasd ajsdlksajl asdklsakl kljkljasd. https://www.gmail.com asdasd khkasdh.";
Regex rex = new Regex("(http|https|ftp|mailto)://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?");
MatchCollection Matches = rex.Matches(strContent);
foreach (Match NextMatch in Matches)
{
      string shortUrlText = NextMatch.Value ;
      if (NextMatch.Value.Length > 100)
          shortUrlText = NextMatch.Value.Substring(0, 100);
      strContent = strContent.Replace(NextMatch.Value, String.Format ("<a href=\"{0}\">"+ shortUrlText +"</a>",NextMatch .Value));
}

 

Responses
No responses found for this thread. Be the first to respond this thread.
Post Reply
Login to post Response.