如何在swift中編碼字符串以刪除所有特殊字符並將其替換爲其匹配的html編號。將字符串編碼爲HTML字符串Swift 3
可以說我有以下字符串:
var mystring = "This is my String & That's it."
,然後替換它的HTML數
& = &
' = '
> = >
特殊字符,但我想對所有特殊字符不只是那些做列在上面的字符串中。這將如何完成?
如何在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