将文章内容中没有链接的地址转换为链接。
代码如下:
public static string ShowUrls(string text)
{
//代码来自博客园 http://www.cnblogs.com
Regex linkRegex = new Regex(" href\\s*=\\s*(?:(?:\\\"(?<url>[^\\\"]*)\\\")|(?<url>[^\\s]*))",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
MatchCollection linkMatchs = linkRegex.Matches(text);
string pattern = @"(http|ftp|https):\/\/[\w]+(.[\w]+)([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])";
MatchCollection matchs;
string clearText = Regex.Replace(text, "(<br>|<br/>)"," ", RegexOptions.IgnoreCase);
clearText = Regex.Replace(clearText, "<[^>]*>", string.Empty, RegexOptions.Compiled);//清除html标记
matchs = Regex.Matches(clearText, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
bool flag1 = true;
for(int i=0;i<matchs.Count;i++)
{
Match m = matchs[i];
string link = "<a href=\"" + m.ToString() + "\" target=\"_blank\">" + m.ToString() + "</a>";
if (linkMatchs.Count > 0)
{
foreach (Match linkMatch in linkMatchs)
{
if (linkMatch.Value.IndexOf(m.Value) > -1)
{
flag1 = false;
break;
}
}
}
if(flag1)
{
bool flag2 = true;
for (int j = 0; j < i; j++)
{
if (m.ToString() == matchs[j].ToString())
{
flag2 = false;
}
}
if (flag2)
{
text = text.Replace(m.ToString(), link);
}
}
}
return text;
}