1 Star 0 Fork 0

tuboyou/c2

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
html.go 2.89 KB
一键复制 编辑 原始数据 按行查看 历史
tuboyou 提交于 2025-03-10 18:02 +08:00 . 添加注释
package u2
import (
"regexp"
)
var (
htmlDecodeMap = map[string]string{
"&": "&",
"&lt;": "<",
"&gt;": ">",
"&quot;": "\"",
"&#39;": "'",
"&#40;": "(",
"&#41;": ")",
"&nbsp;": " ",
"&copy;": "©",
"&reg;": "®",
"&trade;": "™",
"&times;": "×",
"&divide;": "÷",
"&mdash;": "—",
"&ndash;": "–",
"&hellip;": "…",
"&laquo;": "«",
"&raquo;": "»",
"&lsaquo;": "‹",
"&rsaquo;": "›",
"&ldquo;": "“",
"&rdquo;": "”",
"&lsquo;": "‘",
"&rsquo;": "’",
"&sbquo;": "‚",
"&bdquo;": "„",
"&permil;": "‰",
"&euro;": "€",
"&pound;": "£",
"&curren;": "¤",
"&yen;": "¥",
"&sect;": "§",
"&para;": "¶",
"&middot;": "·",
"&bull;": "•",
"&dagger;": "†",
}
htmlEncodeMap = map[string]string{
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
"\"": "&quot;",
"'": "&#39;",
"(": "&#40;",
")": "&#41;",
" ": "&nbsp;",
"©": "&copy;",
"®": "&reg;",
"™": "&trade;",
"×": "&times;",
"÷": "&divide;",
"—": "&mdash;",
"–": "&ndash;",
"…": "&hellip;",
"«": "&laquo;",
"»": "&raquo;",
"‹": "&lsaquo;",
"›": "&rsaquo;",
"“": "&ldquo;",
"”": "&rdquo;",
"‘": "&lsquo;",
"’": "&rsquo;",
"‚": "&sbquo;",
"„": "&bdquo;",
"‰": "&permil;",
"€": "&euro;",
"£": "&pound;",
"¤": "&curren;",
"¥": "&yen;",
"§": "&sect;",
"¶": "&para;",
"·": "&middot;",
"•": "&bull;",
"†": "&dagger;",
}
// 按长度降序排列,确保长实体优先匹配
htmlDecodePattern = regexp.MustCompile(`&(?:amp|lt|gt|quot|#39|#40|#41|nbsp|copy|reg|trade|times|divide|mdash|ndash|hellip|laquo|raquo|lsaquo|rsaquo|ldquo|rdquo|lsquo|rsquo|sbquo|bdquo|permil|euro|pound|curren|yen|sect|para|middot|bull|dagger);`)
htmlEncodePattern = regexp.MustCompile(`[&<>"'() ©®™×÷—–…«»‹›“”‘’‚„‰€£¤¥§¶·•†]`)
)
// HtmlDecode 将包含HTML实体的字符串转换为普通字符串。
//
// 参数:
//
// input - 包含HTML实体的字符串
//
// 返回值:
//
// 转换后的普通字符串
//
// 示例:
//
// decoded := HtmlDecode("&lt;div&gt;") // 返回 "<div>"
func HtmlDecode(input string) string {
return htmlDecodePattern.ReplaceAllStringFunc(input, func(match string) string {
if replacement, ok := htmlDecodeMap[match]; ok {
return replacement
}
return match
})
}
// HtmlEncode 将普通字符串转换为包含HTML实体的字符串。
//
// 参数:
//
// input - 需要编码的普通字符串
//
// 返回值:
//
// 包含HTML实体的字符串
//
// 示例:
//
// encoded := HtmlEncode("<div>") // 返回 "&lt;div&gt;"
func HtmlEncode(input string) string {
return htmlEncodePattern.ReplaceAllStringFunc(input, func(match string) string {
if replacement, ok := htmlEncodeMap[match]; ok {
return replacement
}
return match
})
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/tuboyou/c2.git
git@gitee.com:tuboyou/c2.git
tuboyou
c2
c2
v0.0.4

搜索帮助