我NSString
里面有很多HTML文字。该字符串的长度大于3.500.000个字符。我该如何将HTML文本转换为NSString
纯文本格式。我正在使用扫描仪,但是它工作太慢。任何想法 ?
这取决于您要定位的iOS版本。从iOS7开始,有一个内置方法,该方法不仅会剥离HTML标签,而且还会将格式设置为字符串:
Xcode 9 /迅捷4
if let htmlStringData = htmlString.data(using: .utf8), let attributedString = try? NSAttributedString(data: htmlStringData, options: [.documentType : NSAttributedString.DocumentType.html], documentAttributes: nil) {
print(attributedString)
}
您甚至可以创建如下扩展名:
extension String {
var htmlToAttributedString: NSAttributedString? {
guard let data = self.data(using: .utf8) else {
return nil
}
do {
return try NSAttributedString(data: data, options: [.documentType : NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
print("Cannot convert html string to attributed string: \(error)")
return nil
}
}
}
请注意,此示例代码正在使用UTF8编码。您甚至可以创建函数而不是计算属性,然后将编码添加为参数。
迅捷3
let attributedString = try NSAttributedString(data: htmlString.dataUsingEncoding(NSUTF8StringEncoding)!,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
目标C
[[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]} documentAttributes:nil error:nil];
如果只需要删除<
和之间的所有内容>
(肮脏的方式!!!),如果字符串中包含这些字符,则可能会出现问题,请使用以下命令:
- (NSString *)stringByStrippingHTML {
NSRange r;
NSString *s = [[self copy] autorelease];
while ((r = [s rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
s = [s stringByReplacingCharactersInRange:r withString:@""];
return s;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句