一般来说,干这种事正则才是王道。不过在ios上执行的效率貌似也高不了多少(第三方类库是在Obj-C的基础上写的),所以弄个一般的方法,基本满足需求就可以了。
废话不多说,直接上代码(google上能找到很多一样的代码)
- (NSString *)flattenHTML:(NSString *)html trimWhiteSpace:(BOOL)trim {
NSScanner *theScanner = [NSScanner scannerWithString:html];
NSString *text = nil;
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:@""];
}
// trim off whitespace
return trim ? [html stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] : html;
}