初始
This commit is contained in:
77
third/richText/strip.go
Normal file
77
third/richText/strip.go
Normal file
@ -0,0 +1,77 @@
|
||||
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 with empty string
|
||||
reNbsp := regexp.MustCompile(` `)
|
||||
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()
|
||||
}
|
Reference in New Issue
Block a user