Files
zmkgC/third/richText/strip.go
2025-07-07 20:11:59 +08:00

78 lines
2.1 KiB
Go
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package richtext
import (
"fmt"
"regexp"
"strings"
)
func RemoveRichText(text string) string {
// Regular expression to replace <br/> and <p> tags with newline
reBr := regexp.MustCompile(`<(br|p)(\s[^>]*)?>`)
text = reBr.ReplaceAllString(text, "\n")
// Add four full-width spaces after each newline
reNewline := regexp.MustCompile(`\n`)
text = reNewline.ReplaceAllString(text, "\n  ") // 两个全角空格等于四个半角空格,即四个汉字的距离
// Regular expression to replace &nbsp; with empty string
reNbsp := regexp.MustCompile(`&nbsp;`)
text = reNbsp.ReplaceAllString(text, "")
// Regular expression to match other HTML tags
re := regexp.MustCompile("<[^>]*>")
plainText := re.ReplaceAllString(text, "")
plainText = strings.TrimSpace(plainText)
// plainText = "  " + plainText
return plainText
}
func ExtractImageURLs(text string) []string {
re := regexp.MustCompile(`<img[^>]+\bsrc=["']([^"']+)["']`)
matches := re.FindAllStringSubmatch(text, -1)
var urls []string
for _, match := range matches {
urls = append(urls, match[1])
}
return urls
}
func ConvertToRichText(plainText string, imageURLs []string) string {
// 将纯文本分割成段落
paragraphs := strings.Split(plainText, "\n")
// 创建一个StringBuilder来构建富文本
var richText strings.Builder
// 将每个段落包装在<p>标签中
for _, paragraph := range paragraphs {
richText.WriteString("<p>")
richText.WriteString(paragraph)
richText.WriteString("</p>")
}
// 将每个图片URL包装在<img>标签中,并附加到富文本中
for _, imageURL := range imageURLs {
richText.WriteString("<img src=\"")
richText.WriteString(imageURL)
richText.WriteString("\" />")
}
// 返回富文本字符串
return richText.String()
}
// 传入一个字符串数组,将其包装为一个富文本图片标签
func ConvertImageURLsToRichText(imageURLs []string) string {
var richText strings.Builder
for _, imageURL := range imageURLs {
richText.WriteString(fmt.Sprintf(`<p><img src="%s" /></p>`, imageURL))
}
return richText.String()
}