当我们遇到后台返回的是一串html'字符串,这个字符串中包含的有imgURL标签和文字,而需要是把文字和图片分别展示出来, 这个时候就需要先把里面的图片url提取出来,然后在使用imageView展示。现在问题的关键是如何把所有的imgURL拿出来呢? 其实很简单, 一个正确的正则表达式 <(img|IMG)(.*?)(/>|></img>|>) 即可实现我们要的效果
顺便附上一个移除html标签的方法
具体代码如下 返回的是这串字符串里面所有的图片地址 所有是一个集合
- (NSArray *)filterImageUrlFromHTML:(NSString *)html
{
NSMutableArray *resultArray = [NSMutableArray array];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<(img|IMG)(.*?)(/>|></img>|>)" options:NSRegularExpressionAllowCommentsAndWhitespace error:nil];
NSArray *result = [regex matchesInString:html options:NSMatchingReportCompletion range:NSMakeRange(0, html.length)];
for (NSTextCheckingResult *item in result) {
NSString *imgHtml = [html substringWithRange:[item rangeAtIndex:0]];
NSArray *tmpArray = nil;
if ([imgHtml rangeOfString:@"src=\""].location != NSNotFound) {
tmpArray = [imgHtml componentsSeparatedByString:@"src=\""];
} else if ([imgHtml rangeOfString:@"src="].location != NSNotFound) {
tmpArray = [imgHtml componentsSeparatedByString:@"src="];
}
if (tmpArray.count >= 2) {
NSString *src = tmpArray[1];
NSUInteger loc = [src rangeOfString:@"\""].location;
if (loc != NSNotFound) {
src = [src substringToIndex:loc];
[resultArray addObject:src];
}
}
}
return resultArray;
}
移除html字符串中的标签
- (NSString *)removeHTMLFromStr:(NSString *)html{
NSArray *components = [html componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
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;
}