2017-02-17 23 views
0

すべての特殊文字を削除して一致するhtml番号に置き換えるには、文字列を迅速にエンコードできますか?文字列をHTML文字列に変換Swift 3

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

と、そのHTML番号

& = & 
' = ' 
> = > 

と特殊文字を置き換えるしかし、私はすべての特殊文字だけでなく、もののためにこれをしたい:

は、私は次の文字列を考えてみましょう上記の文字列にリストされています。これはどのようにして行われますか?

答えて

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: "&#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、私の 'edit'を見てください。 – 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)) 
} 
関連する問題