1

我有一个 NSString,其中包含一些我从 Web 服务中检索的 html。我需要做的是从中删除 html 链接,以便我可以将其显示为纯文本。

我看到了一些与扁平化 html HEREHEREHERE相关的问题。

不幸的是,所有这些方法的共同点是它们从其中剥离了所有 html,包括段落标签,并且所有文本最终都显示为一个单元。

我想要的是有一种方法,只从其中剥离 html 链接并保留段落标签。我怎样才能做到这一点?谢谢!

4

3 回答 3

5

还有另一种方法,适用于 iOS 7 及更高版本:

NSAttributedString* attributedText = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding]
                                                                      options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                                                NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
                                                           documentAttributes:nil
                                                                        error:nil];
NSString* plainText = [attributedText string];
于 2014-09-10T11:37:16.033 回答
1

您可以使用 GTMNSString-HTML。只需从这里下载

将其导入您的项目。现在你使用下面的方法来扁平化 HTML

- (NSString *)stringByConvertingHTMLToPlainText

如果要保留段落标签,请在上述方法中修改dontReplaceTagWithSpace

dontReplaceTagWithSpace = ([tagName isEqualToString:@"p"] || OTHER TAG CHECKINGS....);
于 2013-10-30T04:40:47.780 回答
0

我解决了自己的问题,而无需进行很多更改。我从这个问题中采用了 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;
}

希望这可以帮助!

于 2013-10-30T09:14:59.437 回答