在iOS中删除html标记和不需要的字符

时间:2013-04-15 13:26:15

标签: iphone ios objective-c xcode

我有以下方法从字符串中删除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;
}

我有太多的情况,怎么能以更优雅的方式完成?

3 个答案:

答案 0 :(得分:1)

我相信NSString有一些内置的方法。 Check this answer out.

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

除第一种情况外,你可以像[s stringByReplacingOccurrencesOfString:"&#8221;" withString:@"\""];一样使用。