2017-02-17 107 views
0

如何在swift中編碼字符串以刪除所有特殊字符並將其替換爲其匹配的html編號。將字符串編碼爲HTML字符串Swift 3

可以說我有以下字符串:

var mystring = "This is my String & That's it." 

,然後替換它的HTML數

& = & 
' = ' 
> = > 

特殊字符,但我想對所有特殊字符不只是那些做列在上面的字符串中。這將如何完成?

回答

0

檢查所有特殊字符在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: "&#38") 
     returnStr = returnStr.replacingOccurrences(of: "'", with: "&#39") 
     returnStr = returnStr.replacingOccurrences(of: ">", with: "&#62") 
     ... 


     return returnStr 
    } 
} 

自己動手,創建自己的功能設備。


編輯

如果你認爲它是一個巨大的工作,你檢查:https://github.com/adela-chang/StringExtensionHTML

+0

這是我最初做的,好像有必須是一個簡單的方法來完成這個 – user2423476

+0

@ user2423476,請參閱我的編輯。 – aircraft

0

嘗試SwiftSoup

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 &amp;&lt;&gt; &Aring; &aring; &#x3c0; &#x65b0; there &frac34; &copy; &raquo;", escapedAscii) 
    XCTAssertEqual("Hello &amp;&lt;&gt; &angst; &aring; &pi; &#x65b0; there &frac34; &copy; &raquo;", escapedAsciiFull) 
    XCTAssertEqual("Hello &amp;&lt;&gt; &#xc5; &#xe5; &#x3c0; &#x65b0; there &#xbe; &#xa9; &#xbb;", escapedAsciiXhtml) 
    XCTAssertEqual("Hello &amp;&lt;&gt; Å å π 新 there ¾ © »", escapedUtfFull) 
    XCTAssertEqual("Hello &amp;&lt;&gt; Å å π 新 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)) 
}