html.go 832 B

12345678910111213141516171819202122232425262728293031323334
  1. package utils
  2. import (
  3. "regexp"
  4. "strings"
  5. )
  6. // StripHTML 去除HTML标签,保留纯文本
  7. func StripHTML(html string) string {
  8. // 移除HTML标签
  9. re := regexp.MustCompile(`<[^>]*>`)
  10. text := re.ReplaceAllString(html, "")
  11. // 替换多个空格为一个空格
  12. text = regexp.MustCompile(`\s+`).ReplaceAllString(text, " ")
  13. // 移除特殊字符
  14. text = strings.ReplaceAll(text, "&nbsp;", " ")
  15. text = strings.ReplaceAll(text, "&lt;", "<")
  16. text = strings.ReplaceAll(text, "&gt;", ">")
  17. text = strings.ReplaceAll(text, "&amp;", "&")
  18. text = strings.ReplaceAll(text, "&quot;", "\"")
  19. return strings.TrimSpace(text)
  20. }
  21. // TruncateText 截取指定长度的文本
  22. func TruncateText(text string, length int) string {
  23. runeText := []rune(text)
  24. if len(runeText) <= length {
  25. return text
  26. }
  27. return string(runeText[:length])
  28. }