将字符串编码为HTML字符串Swift 3
问题描述:
如何在swift中编码字符串以删除所有特殊字符并将其替换为其匹配的html编号。将字符串编码为HTML字符串Swift 3
可以说我有以下字符串:
var mystring = "This is my String & That's it."
,然后替换它的HTML数
& = &
' = '
> = >
特殊字符,但我想对所有特殊字符不只是那些做列在上面的字符串中。这将如何完成?
答
检查所有特殊字符在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
答
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))
}
这是我最初做的,好像有必须是一个简单的方法来完成这个 – user2423476
@ user2423476,请参阅我的编辑。 – aircraft