解码HTML字符串 [英] Decode HTML string

查看:197
本文介绍了解码HTML字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何解码我的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

这将 Bj&将 < / em>

如果您只是想转换HTML符号并去掉HTML标签(例如< span> ; / < / span> ),只需抓住字符串

  let string =Bj& ouml; rn is< em> great< / em> name
if let result = string.htmlAttributeString?.string {
print(result) //Björn是个好名字
}






对于之前的Swift版本,请参阅此答案的以前的版本


How can I decode my html string from:

<span>Bj&ouml;rn</span>

to

<span>Björn</span>

in Swift 3 ?

解决方案

Do you really need to preserve the <span> tags, while replacing the &ouml; 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.

In 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)
    }
}

If you want an attributed string (for example, for use in a UILabel)

let string = "Bj&ouml;rn is <em>great</em> name"
label.attributedText = string.htmlAttributedString

This converts Bj&ouml;rn to Björn and italicizes the <em>...</em> portion, too.

If you just want to convert the HTML symbols and strip out the HTML tags (such as your <span>/</span>), just grab the string:

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


For prior Swift versions, see previous revision of this answer.

这篇关于解码HTML字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆