Asp学习站欢迎你!

带HTML的汉字字符串截取函数

来源:ASP学习网 作者:Admin 时间:08-04-15 点击:

  1. <%
  2. '文本段代码
  3. Dim fString
  4. 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>"
  5. %>
如果一段文本段含有Html代码,截取该文本段为10个字符长,相信大家首先使用Len与Left函数,但这些函数识别的中文汉字当做为一个字符,这样输出的结果肯定不会正确。借用自定义函数CutStr......
  1. <%
  2. '用省略号格式化数据标题(兼容中文字)
  3. function CutStr(str,strlen,endStr)
  4. dim cvSt:cvSt=Str
  5. if cvSt="" then
  6. CutStr=""
  7. exit function
  8. end if
  9. dim l,t,c
  10. l=len(cvSt)
  11. t=0
  12. for i=1 to l
  13. c=Abs(Asc(Mid(cvSt,i,1)))
  14. if c>255 then
  15. t=t+2
  16. else t=t+1
  17. end if
  18. if t>=strlen then
  19. cutStr=left(cvSt,i)&endStr
  20. exit for
  21. else cutStr=cvSt
  22. end if
  23. next
  24. cutStr=replace(cutStr,chr(10),"")
  25. cutStr=replace(cutStr,chr(0),"")
  26. end Function
  27. %>

使用CutStr截取:
  1. <%response.write CutStr(fString,10,"...")%>

则输入结果为html代码,并不会显示“中华人民共和国”。显然,结果是错误的!
现在要考虑的先去除Html代码,再截取字符。
给自动删除html代码提供一个函数,使用正则表达式:
  1. <%
  2. '去掉HTML标记
  3. Public Function Replacehtml(Textstr)
  4. Dim Str,re
  5. Str=Textstr
  6. Set re=new RegExp
  7. re.IgnoreCase =True
  8. re.Global=True
  9. re.Pattern="<(.[^>]*)>"
  10. Str=re.Replace(Str, "")
  11. Set Re=Nothing
  12. Replacehtml=Str
  13. End Function
  14. %>

然后再截取字符,整个代码如下:
    <%
  1. '去掉HTML标记
  2. Public Function Replacehtml(Textstr)
  3. Dim Str,re
  4. Str=Textstr
  5. Set re=new RegExp
  6. re.IgnoreCase =True
  7. re.Global=True
  8. re.Pattern="<(.[^>]*)>"
  9. Str=re.Replace(Str, "")
  10. Set Re=Nothing
  11. Replacehtml=Str
  12. End Function  '用省略号格式化数据标题(兼容中文字)
  13. function CutStr(str,strlen,endStr)
  14. dim cvSt:cvSt=Str
  15. if cvSt="" then
  16. CutStr=""
  17. exit function
  18. end if
  19. dim l,t,c
  20. l=len(cvSt)
  21. t=0
  22. for i=1 to l
  23. c=Abs(Asc(Mid(cvSt,i,1)))
  24. if c>255 then
  25. t=t+2
  26. else t=t+1
  27. end if
  28. if t>=strlen then
  29. cutStr=left(cvSt,i)&endStr
  30. exit for
  31. else cutStr=cvSt
  32. end if
  33. next
  34. cutStr=replace(cutStr,chr(10),"")
  35. cutStr=replace(cutStr,chr(0),"")
  36. end Function </div><div>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>"</div><div>response.write "<font color=red>原来的字符集:</font>" & fString & "<p>"
  37. response.write "<font color=red>去除Html代码的字符:</font>" & Replacehtml(fString) & "<p>"
  38. response.write "<font color=red>转换后的字符:</font>" & CutStr(Replacehtml(fString),14,"")
  39. %>
标签: 截取, 函数】 【打印】 【关闭
最新评论共有 0 位网友发表了评论
发表评论
评论内容:不能超过250字,需审核,请自觉遵守互联网相关政策法规。
用户名: 验证码: 验证码 查看所有评论