Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 22 additions & 26 deletions pkg/htmltext/htmltext.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,38 +34,34 @@ import (
"github.com/mozillazg/go-pinyin"
)

var (
reCode = regexp.MustCompile(`(?ism)<(pre)>.*<\/pre>`)
reCodeReplace = "{code...}"
reLink = regexp.MustCompile(`(?ism)<a.*?[^<]>(.*)?<\/a>`)
reLinkReplace = " [$1] "
reSpace = regexp.MustCompile(` +`)
reSpaceReplace = " "

spaceReplacer = strings.NewReplacer(
"\n", " ",
"\r", " ",
"\t", " ",
)
)

// ClearText clear HTML, get the clear text
func ClearText(html string) (text string) {
if len(html) == 0 {
text = html
return
func ClearText(html string) string {
if html == "" {
return html
}

var (
re *regexp.Regexp
codeReg = `(?ism)<(pre)>.*<\/pre>`
codeRepl = "{code...}"
linkReg = `(?ism)<a.*?[^<]>(.*)?<\/a>`
linkRepl = " [$1] "
spaceReg = ` +`
spaceRepl = " "
)
re = regexp.MustCompile(codeReg)
html = re.ReplaceAllString(html, codeRepl)
html = reCode.ReplaceAllString(html, reCodeReplace)
html = reLink.ReplaceAllString(html, reLinkReplace)

re = regexp.MustCompile(linkReg)
html = re.ReplaceAllString(html, linkRepl)

text = strings.NewReplacer(
"\n", " ",
"\r", " ",
"\t", " ",
).Replace(strip.StripTags(html))
text := spaceReplacer.Replace(strip.StripTags(html))

// replace multiple spaces to one space
re = regexp.MustCompile(spaceReg)
text = strings.TrimSpace(re.ReplaceAllString(text, spaceRepl))
return
return strings.TrimSpace(reSpace.ReplaceAllString(text, reSpaceReplace))
}

func UrlTitle(title string) (text string) {
Expand Down