內容頁超連接關鍵詞的完美實現

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ArticleAdd.aspx.cs" Inherits="ArticleAdd" validateRequest="false" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
   
<title>無標題頁</title>
</head>
<body>
   
<form id="form1" runat="server">
   
<div >
        關 鍵 詞:
       
<br /><asp:TextBox ID="TextBox2" runat="server" Rows="5" width="400" TextMode="MultiLine" Text="春江|海平|明月"></asp:TextBox>
       
<br />
        相應連接:
       
<br /><asp:TextBox ID="TextBox3" runat="server" Rows="5" width="400" TextMode="MultiLine" Text="http://www.jtwq.com/a.aspx|http://www.jtwq.com/b.aspx|http://www.jtwq.com/c.aspx"></asp:TextBox>
       
<br />
        內容輸入:
       
<br /><asp:TextBox ID="TextBox1" runat="server"  Rows="5" width="400" TextMode="MultiLine" Text="春江潮水連海平,海上明月共潮聲。灩灩隨波千萬裏,何處春江無月明。"></asp:TextBox>
       
<br />
       
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
   
</div>
   
</form>
</body>
</html>

 

 

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;

public partial class ArticleAdd : System.Web.UI.Page
{
   
protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e)
    {
       
string v = TextBox1.Text;

        Response.Write(StrInArray(v));

    }

   
private string StrInArray(string v)
    {
       
       
//關鍵詞與URL可以從數據庫中讀取,這裏直接賦值
        string vKey = "春江|海平|明月";//關鍵詞
        string vHref = "http://www.jtwq.com/a.aspx|http://www.jtwq.com/b.aspx|http://www.jtwq.com/c.aspx";//相應的鏈接
        string[] arr1 = vKey.Split(new char[1] { '|' });
       
string[] arr2 = vHref.Split(new char[1] { '|' });

       
string Reg = @"<(a|pre)/b(?:(?!</?/1).)*<//1>";//此正則參考了“lxcnn”的寫法
        MatchCollection mc = Regex.Matches(v, Reg, RegexOptions.IgnoreCase);
       
string[] MatchVale = new string[mc.Count];
       
int i = 0;
       
foreach (Match m in mc)
        {
            MatchVale[i
++] = m.Groups[0].Value.ToLower().Trim();
            v
= v.Replace(m.Groups[0].Value.ToLower().Trim(), "tmpStr" + (i - 1));
        }

       
for (int ii = 0; ii < arr1.Length; ii++)
        {
           v
= v.Replace(arr1[ii], "<a href=/"" + arr2[ii] + "/">" + arr1[ii] + "</a>");
        }

       
for (int iii = 0; iii < MatchVale.Length; iii++)
        {
            v
= v.Replace("tmpStr" + iii, MatchVale[iii]);
        }

       
return v;
    }
   
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章