This commit is contained in:
xing 2022-09-25 01:44:45 +08:00
parent 6a42a23ef5
commit 1dc9d796fa
3 changed files with 9 additions and 26 deletions

View File

@ -135,7 +135,7 @@ func StripTagsX(str, allowable string) string {
}
var tagx = regexp.MustCompile(`(</?[a-z0-9]+?)( |>)`)
var selfCloseTags = []string{"area", "base", "basefont", "br", "col", "command", "embed", "frame", "hr", "img", "input", "isindex", "link", "meta", "param", "source", "track", "wbr"}
var selfCloseTags = map[string]string{"area": "", "base": "", "basefont": "", "br": "", "col": "", "command": "", "embed": "", "frame": "", "hr": "", "img": "", "input": "", "isindex": "", "link": "", "meta": "", "param": "", "source": "", "track": "", "wbr": ""}
func CloseHtmlTag(str string) string {
tags := tag.FindAllString(str, -1)
@ -147,13 +147,13 @@ func CloseHtmlTag(str string) string {
ss := strings.TrimSpace(tagx.FindString(s))
if ss[len(ss)-1] != '>' {
ss = fmt.Sprintf("%s>", ss)
if IsContainInArr(ss, selfCloseTags) {
if _, ok := selfCloseTags[ss]; ok {
continue
}
}
tagss = append(tagss, ss)
}
r := SliceMap(ClearClosedTag(tagss), func(s string) string {
r := SliceMap(SliceReverse(ClearClosedTag(tagss)), func(s string) string {
return fmt.Sprintf("</%s>", strings.Trim(s, "<>"))
})
return strings.Join(r, "")

View File

@ -287,6 +287,11 @@ func TestCloseHtmlTag(t *testing.T) {
args: args{str: `<pre class="wp-block-preformatted">GRANT privileges ON databasename.tablename TO 'username'@'h...<p class="read-more"><a href="/p/305">继续阅读</a></p>`},
want: "</pre>",
},
{
name: "t2",
args: args{str: `<pre><div>`},
want: "</div></pre>",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {

View File

@ -46,7 +46,7 @@ func ExceptRaw(str string, limit, id int) string {
break
} else {
content = string(ru[:end])
closeTag := CloseHtmlTag(content)
closeTag := helper.CloseHtmlTag(content)
tmp := `%s......%s<p class="read-more"><a href="/p/%d">继续阅读</a></p>`
if strings.Contains(closeTag, "pre") || strings.Contains(closeTag, "code") {
tmp = `%s%s......<p class="read-more"><a href="/p/%d">继续阅读</a></p>`
@ -66,25 +66,3 @@ func Except(p *Plugin[models.WpPosts], c *gin.Context, post *models.WpPosts, sce
post.PostContent = ExceptRaw(post.PostContent, limit, int(post.Id))
}
var tagx = regexp.MustCompile(`(</?[a-z0-9]+?)( |>)`)
var tagAllow = regexp.MustCompile(`<(a|b|blockquote|cite|code|dd|del|div|dl|dt|em|h1|h2|h3|h4|h5|h6|i|li|ol|p|pre|span|strong|ul).*?>`)
func CloseHtmlTag(str string) string {
tags := tagAllow.FindAllString(str, -1)
if len(tags) < 1 {
return str
}
var tagss = make([]string, 0, len(tags))
for _, s := range tags {
ss := strings.TrimSpace(tagx.FindString(s))
if ss[len(ss)-1] != '>' {
ss = fmt.Sprintf("%s>", ss)
}
tagss = append(tagss, ss)
}
r := helper.SliceMap(helper.ClearClosedTag(tagss), func(s string) string {
return fmt.Sprintf("</%s>", strings.Trim(s, "<>"))
})
return strings.Join(r, "")
}