解码HTML字符串 [英] Decode HTML string
问题描述
如何解码我的html字符串: b
< span> Bj& ouml; rn< / span>
至
<跨度>&比约恩LT; /跨度>
在Swift 3中?
您真的需要保留< span>
标签,同时替换& ouml;
符号? Leo Dabus在将Unicode符号或其XML / HTML实体转换为Swift中的Unicode编号中提出的一种技术将转换符号包括通过一个属性字符串往返。
在Swift 4中:
扩展字符串{
///将HTML字符串转换为`NSAttributedString`
var htmlAttributedString:NSAttributedString? {
返回尝试? NSAttributedString(data:Data(utf8),options:[.documentType:NSAttributedString.DocumentType.html,.characterEncoding:String.Encoding.utf8.rawValue],documentAttributes:nil)
}
}
如果您想要一个属性字符串(例如,用于 UILabel
pre $ let string =Bj& ouml; rn是< em>很棒的< / em>名称
label.attributedText = string.htmlAttributedString
这将 如果您只是想转换HTML符号并去掉HTML标签(例如 对于之前的Swift版本,请参阅此答案的以前的版本。 How can I decode my html string from: to in Swift 3 ? Do you really need to preserve the In Swift 4: If you want an attributed string (for example, for use in a This converts If you just want to convert the HTML symbols and strip out the HTML tags (such as your
For prior Swift versions, see previous revision of this answer. 这篇关于解码HTML字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! Bj&将
< / em> $ c
< span> ;
/ < / span>
),只需抓住字符串
:
let string =Bj& ouml; rn is< em> great< / em> name
if let result = string.htmlAttributeString?.string {
print(result) //Björn是个好名字
}
<span>Björn</span>
<span>Björn</span>
<span>
tags, while replacing the ö
symbol? One technique, suggested by Leo Dabus in Convert Unicode symbol or its XML/HTML entities into its Unicode number in Swift, converts the symbols includes round-tripping it through an attributed string.extension String {
/// Converts HTML string to a `NSAttributedString`
var htmlAttributedString: NSAttributedString? {
return try? NSAttributedString(data: Data(utf8), options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
}
}
UILabel
)let string = "Björn is <em>great</em> name"
label.attributedText = string.htmlAttributedString
Björn
to Björn
and italicizes the <em>...</em>
portion, too.<span>
/</span>
), just grab the string
:let string = "Björn is <em>great</em> name"
if let result = string.htmlAttributedString?.string {
print(result) // "Björn is great name"
}