Reputation: 712
I am currently displaying the content of a string inside a pre tag, but I have to elaborate a function that for each link into the string replace it with a link tag, I tried several string replace and regex methods, but no one worked.
string myString = "Bla bla bla bla http://www.site.com and bla bla http://site2.com blabla"
//Logic
string outputString = "Bla bla bla bla <a href="http://www.site.com" target="blank">http://www.site.com</a> and bla bla <a href="http://site2.com" target="blank">http://site2.com</a> blabla"
I have used the following code, but it does not work for every url:
string orderedString = item.Details.Replace("|", "\n" );
string orderedStringWithUrl = "";
System.Text.RegularExpressions.Regex regx = new System.Text.RegularExpressions.Regex("http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.MatchCollection mactches = regx.Matches(orderedString);
foreach (System.Text.RegularExpressions.Match match in mactches)
{
orderedStringWithUrl = orderedString.Replace(match.Value, "<a href='" + match.Value + "' target='blank'>" + match.Value + "</a>");
}
Any suggestion?
Update: I have noticed that the URLs I have in the string are all without spaces and all starts with http or https. Is it an idea the one to put into a everything that starts with http or https up to (and not included) the first space? In that case how can I use the .replace to achieve this?
Tnx in advance.
Upvotes: 3
Views: 6146
Reputation: 10347
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.
Upvotes: 3
Reputation: 6802
check this out: http://alexlittle.net/blog/2009/06/26/regex-for-replacing-url-with-anchor-tag/
Upvotes: 0