ASP关于截取含有Html代码的文本段

王朝asp·作者佚名  2006-11-24
窄屏简体版  字體: |||超大  

仅是个人在实际运用中碰到的一个小问题,提供一上Juven自己的解决思路。

这应该是开发WEB程序中经常遇到的问题。

<%

'文本段代码

Dim fString

fString = "<P><FONT size=3><SPAN class=jlineheight id=InfoDisp1_labContent style=""FONT-SIZE: 15px; COLOR: black"">中华人民共和国</SPAN></FONT></P><P><FONT size=3><SPAN class=jlineheight style=""FONT-SIZE: 15px; COLOR: black"">中华人民共和国中华人民共和国中华人民共和国</B></SPAN></FONT></P>"

%>

如果一段文本段含有Html代码,截取该文本段为10个字符长,相信大家首先使用Len与Left函数,但这些函数识别的中文汉字当做为一个字符,这样输出的结果肯定不会正确。借用自定义函数CutStr......

<%

'用省略号格式化数据标题(兼容中文字)

function CutStr(str,strlen,endStr)

dim cvSt:cvSt=Str

if cvSt="" then

CutStr=""

exit function

end if

dim l,t,c

l=len(cvSt)

t=0

for i=1 to l

c=Abs(Asc(Mid(cvSt,i,1)))

if c>255 then

t=t+2

else t=t+1

end if

if t>=strlen then

cutStr=left(cvSt,i)&endStr

exit for

else cutStr=cvSt

end if

next

cutStr=replace(cutStr,chr(10),"")

cutStr=replace(cutStr,chr(0),"")

end Function

%>

使用CutStr截取:

<%response.write CutStr(fString,10,"...")%>

则输入结果为html代码,并不会显示“中华人民共和国”。显然,结果是错误的!

现在要考虑的先去除Html代码,再截取字符。

给自动删除html代码提供一个函数,使用正则表达式:

<%

'去掉HTML标记

Public Function Replacehtml(Textstr)

Dim Str,re

Str=Textstr

Set re=new RegExp

re.IgnoreCase =True

re.Global=True

re.Pattern="<(.[^>]*)>"

Str=re.Replace(Str, "")

Set Re=Nothing

Replacehtml=Str

End Function

%>

然后再截取字符,整个代码如下:

<%

'去掉HTML标记

Public Function Replacehtml(Textstr)

Dim Str,re

Str=Textstr

Set re=new RegExp

re.IgnoreCase =True

re.Global=True

re.Pattern="<(.[^>]*)>"

Str=re.Replace(Str, "")

Set Re=Nothing

Replacehtml=Str

End Function

'用省略号格式化数据标题(兼容中文字)

function CutStr(str,strlen,endStr)

dim cvSt:cvSt=Str

if cvSt="" then

CutStr=""

exit function

end if

dim l,t,c

l=len(cvSt)

t=0

for i=1 to l

c=Abs(Asc(Mid(cvSt,i,1)))

if c>255 then

t=t+2

else t=t+1

end if

if t>=strlen then

cutStr=left(cvSt,i)&endStr

exit for

else cutStr=cvSt

end if

next

cutStr=replace(cutStr,chr(10),"")

cutStr=replace(cutStr,chr(0),"")

end Function

Dim fString : fString = "<P><FONT size=3><SPAN class=jlineheight id=InfoDisp1_labContent style=""FONT-SIZE: 15px; COLOR: black"">中华人民共和国</SPAN></FONT></P><P><FONT size=3><SPAN class=jlineheight style=""FONT-SIZE: 15px; COLOR: black"">中华人民共和国中华人民共和国中华人民共和国</B></SPAN></FONT></P>"

response.write "<font color=red>原来的字符集:</font>" & fString & "<p>"

response.write "<font color=red>去除Html代码的字符:</font>" & Replacehtml(fString) & "<p>"

response.write "<font color=red>转换后的字符:</font>" & CutStr(Replacehtml(fString),14,"")

%>

最后对文本段fString截取前10个字符,真正显示的结果就是“中华人民共和国”。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航