微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

解码HTML字符串

参见英文答案 > Convert Unicode symbol or its XML/HTML entities into its Unicode number in Swift2个
如何解码我的html字符串:
<span>Bj&ouml;rn</span>

<span>Björn</span>

在Swift 3?

解决方法

你真的需要保留< span>标签,同时替换& ouml;符号? Leo Dabus在 Convert Unicode symbol or its XML/HTML entities into its Unicode number in Swift中提出的一种技术转换符号包括通过属性字符串将其往返.

在Swift 4中:

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&ouml;rn is <em>great</em> name"
label.attributedText = string.htmlAttributedString()

这将Bj& ouml; rn转换为Björn并将< em> …< / em>斜体化为斜体.部分也是.

如果您只想转换HTML符号并删除HTML标记(例如< span> /< / span>),只需抓住字符串:

let string = "Bj&ouml;rn is <em> great </em> name"
if let result = string.htmlAttributedString()?.string {

    print(result)   // "Björn is great name"
}

对于之前的Swift版本,请参阅此答案的previous revision.

原文地址:https://www.jb51.cc/html/228264.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐