gf/encoding/ghtml/ghtml.go

60 lines
1.6 KiB
Go
Raw Normal View History

// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
2017-12-29 16:03:30 +08:00
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
2017-12-29 16:03:30 +08:00
2019-01-15 23:27:47 +08:00
// Package ghtml provides useful API for HTML content handling.
2017-11-23 10:21:28 +08:00
package ghtml
2018-09-04 13:39:12 +08:00
import (
2019-06-19 09:06:52 +08:00
"html"
"strings"
2019-07-29 21:01:19 +08:00
strip "github.com/grokify/html-strip-tags-go"
2018-09-04 13:39:12 +08:00
)
2017-11-23 10:21:28 +08:00
// StripTags strips HTML tags from content, and returns only text.
// Referer: http://php.net/manual/zh/function.strip-tags.php
2018-09-04 13:39:12 +08:00
func StripTags(s string) string {
2019-06-19 09:06:52 +08:00
return strip.StripTags(s)
2018-09-04 13:39:12 +08:00
}
// Entities encodes all HTML chars for content.
// Referer: http://php.net/manual/zh/function.htmlentities.php
2018-09-04 13:39:12 +08:00
func Entities(s string) string {
2019-06-19 09:06:52 +08:00
return html.EscapeString(s)
2018-09-04 13:39:12 +08:00
}
// EntitiesDecode decodes all HTML chars for content.
// Referer: http://php.net/manual/zh/function.html-entity-decode.php
2018-09-04 13:39:12 +08:00
func EntitiesDecode(s string) string {
2019-06-19 09:06:52 +08:00
return html.UnescapeString(s)
2018-09-04 13:39:12 +08:00
}
// SpecialChars encodes some special chars for content, these special chars are:
// "&", "<", ">", `"`, "'".
// Referer: http://php.net/manual/zh/function.htmlspecialchars.php
2017-11-23 10:21:28 +08:00
func SpecialChars(s string) string {
2019-06-19 09:06:52 +08:00
return strings.NewReplacer(
"&", "&amp;",
"<", "&lt;",
">", "&gt;",
`"`, "&#34;",
"'", "&#39;",
).Replace(s)
2017-11-23 10:21:28 +08:00
}
// SpecialCharsDecode decodes some special chars for content, these special chars are:
// "&", "<", ">", `"`, "'".
// Referer: http://php.net/manual/zh/function.htmlspecialchars-decode.php
2017-11-23 10:21:28 +08:00
func SpecialCharsDecode(s string) string {
2019-06-19 09:06:52 +08:00
return strings.NewReplacer(
"&amp;", "&",
"&lt;", "<",
"&gt;", ">",
"&#34;", `"`,
"&#39;", "'",
).Replace(s)
2017-11-23 10:21:28 +08:00
}