如何在Swift中对字符串进行编码以删除所有特殊字符并将其替换为相应的HTML数字。
假设我有以下字符串:
var mystring = "This is my String & That's it."
然后使用其HTML编号替换特殊字符
& = &
' = '
> = >
但我希望对所有特殊字符进行此操作,而不仅仅是上面字符串中列出的字符。如何做到这一点?
extension String {
func makeHTMLfriendly() -> String {
var finalString = ""
for char in self {
for scalar in String(char).unicodeScalars {
finalString.append("&#\(scalar.value)")
}
}
return finalString
}
}
使用方法:
newString = oldString.makeHTMLfriendly()
总的来说,这似乎是有效的(尽管我不确定Unicode标量是否始终与HTML数字匹配)。
请注意,它会将所有东西转换,包括那些实际上不需要转换的字母数字字符。也许可以轻松地编辑它以避免转换一些内容。
func testEscape()throws {
let text = "Hello &<> Å å π 新 there ¾ © »"
let escapedAscii = Entities.escape(text, OutputSettings().encoder(String.Encoding.ascii).escapeMode(Entities.EscapeMode.base))
let escapedAsciiFull = Entities.escape(text, OutputSettings().charset(String.Encoding.ascii).escapeMode(Entities.EscapeMode.extended))
let escapedAsciiXhtml = Entities.escape(text, OutputSettings().charset(String.Encoding.ascii).escapeMode(Entities.EscapeMode.xhtml))
let escapedUtfFull = Entities.escape(text, OutputSettings().charset(String.Encoding.utf8).escapeMode(Entities.EscapeMode.extended))
let escapedUtfMin = Entities.escape(text, OutputSettings().charset(String.Encoding.utf8).escapeMode(Entities.EscapeMode.xhtml))
XCTAssertEqual("Hello &<> Å å π 新 there ¾ © »", escapedAscii)
XCTAssertEqual("Hello &<> Å å π 新 there ¾ © »", escapedAsciiFull)
XCTAssertEqual("Hello &<> Å å π 新 there ¾ © »", escapedAsciiXhtml)
XCTAssertEqual("Hello &<> Å å π 新 there ¾ © »", escapedUtfFull)
XCTAssertEqual("Hello &<> Å å π 新 there ¾ © »", escapedUtfMin)
// odd that it's defined as aring in base but angst in full
// round trip
XCTAssertEqual(text, try Entities.unescape(escapedAscii))
XCTAssertEqual(text, try Entities.unescape(escapedAsciiFull))
XCTAssertEqual(text, try Entities.unescape(escapedAsciiXhtml))
XCTAssertEqual(text, try Entities.unescape(escapedUtfFull))
XCTAssertEqual(text, try Entities.unescape(escapedUtfMin))
}
为了更多的变化:
extension String {
var htmlCompatibleDecimalEncoded: String {
self.unicodeScalars.reduce(into: "") { partialResult, scalar in
partialResult.append(
scalar.properties.isPatternSyntax ? "&#\(scalar.value)" : .init(scalar)
)
// For percent encoded hex-replacements we could use this:
// "%\(String(scalar.value, radix: 16, uppercase: true))"
// But there is a more convenient method for that.
}
}
func htmlCompatiblePercentEncoded(allowing allowedCharacters: CharacterSet = []) -> String {
self.addingPercentEncoding(withAllowedCharacters: allowedCharacters) ?? self
}
}
let my: String = #"This is my "String" & That's it / <or is it?>"#
my.htmlCompatibleDecimalEncoded // "This is my "String" & That's it / <or is it?>"
my.htmlCompatiblePercentEncoded(allowing: .urlQueryAllowed) // "This%20is%20my%20%22String%22%20&%20That's%20it%20/%20%3Cor%20is%20it?%3E"
my.htmlCompatiblePercentEncoded() // "%54%68%69%73%20%69%73%20%6D%79%20%22%53%74%72%69%6E%67%22%20%26%20%54%68%61%74%27%73%20%69%74%20%2F%20%3C%6F%72%20%69%73%20%69%74%3F%3E"
let allowed: CharacterSet = .whitespaces.union(.alphanumerics)
my.htmlCompatiblePercentEncoded(allowing: allowed) // "This is my %22String%22 %26 That%27s it %2F %3Cor is it%3F%3E"
let encodedValue = yourValue.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
检查HTML中的所有特殊字符:
http://www.ascii.cl/htmlcodes.htm
你可以创建一个用于解析字符的工具:import UIKit
类Util:NSObject {
func parseSpecialStrToHtmlStr(oriStr: String) -> String {
var returnStr: String = oriStr
returnStr = returnStr.replacingOccurrences(of: "&", with: "&")
returnStr = returnStr.replacingOccurrences(of: "'", with: "'")
returnStr = returnStr.replacingOccurrences(of: ">", with: ">")
...
return returnStr
}
}
自己动手,打造属于自己的功能设备。
编辑
如果您认为这是一项巨大的工作,请查看此链接:https://github.com/adela-chang/StringExtensionHTML