您的位置:首页 > 移动开发 > IOS开发

iOS字符串NSString 过滤HTML标签的两种方法

2014-09-06 15:43 671 查看
//第一种,用NSScanner扫描,来自下面这个著名的链接,不过现在打不开鸟~

// Source: http://rudis.net/content/2009/01/21/flatten-html-content-ie-strip-tags-cocoaobjective-c

- (NSString *)removeHTML:(NSString *)html {

NSScanner *theScanner;

NSString *text = nil;



theScanner = [NSScanner scannerWithString:html];



while ([theScanner isAtEnd] == NO) {

// find start of tag

[theScanner scanUpToString:@"<" intoString:NULL] ;



// find end of tag

[theScanner scanUpToString:@">" intoString:&text] ;



// replace the found tag with a space

//(you can filter multi-spaces out later if you wish)

html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",
text]withString:@" "];



}

return html;

}

//第二种,用NSString自带的Seprated自截断方法

- (NSString *)removeHTML2:(NSString *)html{

NSArray *components = [html componentsSeparatedByCharactersInSet:[NSCharacterSetcharacterSetWithCharactersInString:@"<>"]];



NSMutableArray *componentsToKeep = [NSMutableArray array];

for (int i = 0; i < [components count]; i = i + 2)
{

[componentsToKeep addObject:[components objectAtIndex:i]];

}



NSString *plainText = [componentsToKeep componentsJoinedByString:@""];

return plainText;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: