【问题标题】:iOS NSString Flatten Html While Keeping The Paragraph TagsiOS NSString 在保留段落标签的同时展平 Html
【发布时间】:2013-10-30 04:26:30
【问题描述】:
我有一个 NSString,其中包含我从 Web 服务检索的一些 html。我需要做的是从中删除 html 链接,以便我可以将其显示为纯文本。
我看到了一些与扁平化html相关的问题HERE、HERE和HERE。
不幸的是,所有这些方法的共同点是它们会从中剥离所有 html,包括段落标签,并且所有文本最终都显示为一个单元。
我想要的是有一个方法,只从其中剥离 html 链接并保留段落标签。我怎样才能做到这一点?谢谢!
【问题讨论】:
标签:
ios
iphone
objective-c
nsstring
【解决方案1】:
还有另一种方法,适用于 iOS 7 及更高版本:
NSAttributedString* attributedText = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding]
options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
documentAttributes:nil
error:nil];
NSString* plainText = [attributedText string];
【解决方案2】:
您可以使用 GTMNSString-HTML。只需从here下载
将其导入您的项目。现在你使用下面的方法来扁平化 HTML
- (NSString *)stringByConvertingHTMLToPlainText
如果要保留段落标签,请在上述方法中修改 dontReplaceTagWithSpace
dontReplaceTagWithSpace = ([tagName isEqualToString:@"p"] || OTHER TAG CHECKINGS....);
【解决方案3】:
我解决了自己的问题,而无需进行大量更改。我从THIS QUESTION 中采用了 flattenHtml 方法,并进行了一项修改以保留段落标签。而不是只使用“
- (NSString *)flattenHTML:(NSString *)html {
NSScanner *theScanner;
NSString *text = nil;
theScanner = [NSScanner scannerWithString:html];
while ([theScanner isAtEnd] == NO) {
[theScanner scanUpToString:@"<a" intoString:NULL] ;
[theScanner scanUpToString:@">" intoString:&text] ;
html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>", text] withString:@""];
}
//
html = [html stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
return html;
}
希望这会有所帮助!