最近在工作中遇到后台返回的json串带有html标签,为此找到了相应的方法去掉标签,目前测试所有标签均能去掉,如有不能的请告知。
html为json串中带有html标签的string类型。
- 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 stringByReplacingOccurre ncesOfString: -
[ NSString stringWithFormat:@"%@>", text] -
withString:@""];
如果解析出来还带有\n \t \r之类的再在此基础上用""替代掉。如下:
- NSMutableString *s = [NSMutableString stringWithString:
html]; -
[s replaceOccurrencesOfStri ng:@“ “ withString:@“” options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])]; -
[s replaceOccurrencesOfStri ng:@“\\r” withString:@“” options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])]; -
[s replaceOccurrencesOfStri ng:@“\t” withString:@“” options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])]; -
[s replaceOccurrencesOfStri ng:@“\\n” withString:@“” options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])]; -
[s replaceOccurrencesOfStri ng:@“+” withString:@“” options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];