2017-02-17 136 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)) 
}