仅是个人在实际运用中碰到的一个小问题,提供一上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个字符,真正显示的结果就是“中华人民共和国”。
|