如何在swift中编码字符串以删除所有特殊字符并将其替换为匹配的html编号。
假设我有以下字符串:
var mystring = "This is my String & That's it."
然后用其html编号替换特殊字符
& = &
' = '
> = >
但我想对所有特殊字符执行此操作,而不仅仅是上面字符串中列出的字符。怎么会这样做?
答案 0 :(得分:1)
这是最简单的方法:
DateTime Class1 Class2 Class3 Class4.........Class15
2017-10-01 00:00:00 0 240 17 0 ......... 0
2017-10-01 00:01:00 0 209 14 0 ......... 0
....
and so on
答案 1 :(得分:1)
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数字匹配)。
请注意,它会转换所有内容,甚至包括不需要转换的字母数字字符。编辑它以便不转换某些东西可能不会太困难。
答案 2 :(得分:0)
检查html中的所有特殊字符:
http://www.ascii.cl/htmlcodes.htm
您创建了一个用于解析字符的Util:
像这样: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
答案 3 :(得分:0)
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))
}