util.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // clear
  2. package main
  3. import (
  4. "regexp"
  5. "strings"
  6. )
  7. var at = rune('&')
  8. var ed = rune(';')
  9. var lableMap = map[string]rune{
  10. "&": rune('&'),
  11. " ": rune(' '),
  12. ">": rune('>'),
  13. "&lt;": rune('<'),
  14. }
  15. func CleanString(input string) string {
  16. reg := regexp.MustCompile("[^a-zA-Z0-9\u4e00-\u9fa5]+")
  17. cleaned := reg.ReplaceAllString(input, "")
  18. return cleaned
  19. }
  20. // 清洗正文
  21. func CleanDetailText(detail string) string {
  22. detail = regexp.MustCompile(`<!--[\w\W]*?-->`).ReplaceAllString(detail, "")
  23. detail = regexp.MustCompile(`<!--[\\n\\N]*?-->`).ReplaceAllString(detail, "")
  24. detail = CutLableStr(detail)
  25. return detail
  26. }
  27. //处理转义标签
  28. func CutLableStr(con string) string {
  29. for i := 0; i < 3; i++ {
  30. runes := []rune{}
  31. pools := []rune{}
  32. bpool := false
  33. strings.IndexFunc(con, func(s rune) bool {
  34. if !bpool && s == at {
  35. bpool = true
  36. pools = []rune{}
  37. }
  38. if bpool {
  39. pools = append(pools, s)
  40. if s == ed { //结束
  41. lb := lableMap[string(pools)]
  42. if lb != 0 {
  43. runes = append(runes, lb)
  44. } else {
  45. runes = append(runes, pools...)
  46. }
  47. bpool = false
  48. } else if len(pools) > 6 {
  49. bpool = false
  50. runes = append(runes, pools...)
  51. }
  52. } else {
  53. runes = append(runes, s)
  54. }
  55. return false
  56. })
  57. str1 := string(runes)
  58. if i > 0 && con == str1 {
  59. break
  60. }
  61. con = str1
  62. }
  63. return con
  64. }