3

我有以下方法可以从字符串中删除 html 标签和不需要的字符:

-(NSString *) stringByStrippingHTML: (NSString*) s {
NSRange r;
while ((r = [s rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
    s = [s stringByReplacingCharactersInRange:r withString:@""];
while ((r = [s rangeOfString:@"&#8217;" options:NSRegularExpressionSearch]).location != NSNotFound)
    s = [s stringByReplacingCharactersInRange:r withString:@"\'"];
while ((r = [s rangeOfString:@"&#8221;" options:NSRegularExpressionSearch]).location != NSNotFound)
    s = [s stringByReplacingCharactersInRange:r withString:@"\""];
while ((r = [s rangeOfString:@"&#8220;" options:NSRegularExpressionSearch]).location != NSNotFound)
    s = [s stringByReplacingCharactersInRange:r withString:@"\""];
while ((r = [s rangeOfString:@"&#8230;" options:NSRegularExpressionSearch]).location != NSNotFound)
    s = [s stringByReplacingCharactersInRange:r withString:@"..."];
while ((r = [s rangeOfString:@"&#8211;" options:NSRegularExpressionSearch]).location != NSNotFound)
    s = [s stringByReplacingCharactersInRange:r withString:@"-"];

return s;
}

我有太多的 while 案例,如何以更优雅的方式完成?

4

3 回答 3

1

我相信这NSString有一些内置的方法。 检查这个答案。

于 2013-04-15T13:33:09.577 回答
1

google-toolbox-for-mac库(是的,这也适用于 iOS)有一些NSString类别方法可以更有效地取消转义 & 编码字符。看看GTMNSString+HTML

这不会处理第一种情况(剥离 HTML 标记),但对于您正在做的其他替换,它应该是一个更快、更全面的解决方案。

于 2013-04-15T13:52:52.283 回答
0

[s stringByReplacingOccurrencesOfString:"&#8221;" withString:@"\""];除了第一种情况,您可以使用 like 。

于 2013-04-15T13:33:41.860 回答