转自:http://blog.csdn.net/yyixin/archive/2009/07/26/4380877.aspx
<%
@ 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;
}
}