我需要得到没有html标签的字符串。这是这篇原始文本的一部分
.</p>\n\n<p>For a long time, scientists have been opposed to the id我使用
let htmlData = NSString(string: text).data(using: String.Encoding.unicode.rawValue)
let options = [NSAttributedString.DocumentReadingOptionKey.documentType:
NSAttributedString.DocumentType.html]
let attributedString = try? NSMutableAttributedString(data: htmlData ?? Data(),
options: options,
documentAttributes: nil)
print(attributedString.string)问题是,解析器删除了一个\n。我必须得到"\n\n For a long ....“
但结果是“很长一段时间以来,科学家们一直反对用人来描述动物……”这个/n非常重要。
如何从html字符串中移除所有标签?
发布于 2021-07-20 15:56:51
extension String{
var htmlConvertedString : String{
let string = self.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)
return string
}}尝尝这个
像这样调用let val = str.htmlConvertedString
print(val)
发布于 2021-07-22 06:35:29
ViewController.swift
@IBOutlet weak var label: UILabel!
var content = ".</p>\n\n<p>For a long time, scientists have been opposed to the id"
override func viewDidLoad() {
super.viewDidLoad()
let attr = try? NSAttributedString(htmlString: content, font: UIFont.systemFont(ofSize: 17))
label.attributedText = attr
}html扩展
extension NSAttributedString {
convenience init(htmlString html: String, font: UIFont? = nil, useDocumentFontSize: Bool = true) throws {
let options: [NSAttributedString.DocumentReadingOptionKey : Any] = [
.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue
]
let data = html.data(using: .utf8, allowLossyConversion: true)
guard (data != nil), let fontFamily = font?.familyName, let attr = try? NSMutableAttributedString(data: data!, options: options, documentAttributes: nil) else {
try self.init(data: data ?? Data(html.utf8), options: options, documentAttributes: nil)
return
}
let fontSize: CGFloat? = useDocumentFontSize ? nil : font!.pointSize
let range = NSRange(location: 0, length: attr.length)
attr.enumerateAttribute(.font, in: range, options: .longestEffectiveRangeNotRequired) { attrib, range, _ in
if let htmlFont = attrib as? UIFont {
let traits = htmlFont.fontDescriptor.symbolicTraits
var descrip = htmlFont.fontDescriptor.withFamily(fontFamily)
if (traits.rawValue & UIFontDescriptor.SymbolicTraits.traitBold.rawValue) != 0 {
descrip = descrip.withSymbolicTraits(.traitBold)!
}
if (traits.rawValue & UIFontDescriptor.SymbolicTraits.traitItalic.rawValue) != 0 {
descrip = descrip.withSymbolicTraits(.traitItalic)!
}
attr.addAttribute(.foregroundColor, value: UIColor.black, range: NSRange(location: 0, length: attr.length))
attr.addAttribute(.font, value: UIFont(descriptor: descrip, size: fontSize ?? htmlFont.pointSize), range: range)
}
}
self.init(attributedString: attr)
}
}https://stackoverflow.com/questions/68451025
复制相似问题