iOS 截取字符串中的图片
2017-11-08 本文已影响13人
安静就好_
简单粗暴,直接上代码,直接返回一个照片的数组,代码直接拽走就可以用
+(NSArray *) getImageurlFromHtml:(NSString *) webString
{
NSMutableArray * imageurlArray = [NSMutableArray arrayWithCapacity:1];
//标签匹配
NSString *parten = @"<img(.*?)>";
NSError* error = NULL;
NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:parten options:0 error:&error];
NSArray* match = [reg matchesInString:webString options:0 range:NSMakeRange(0, [webString length] - 1)];
for (NSTextCheckingResult * result in match) {
//过去数组中的标签
NSRange range = [result range];
NSString * subString = [webString substringWithRange:range];
//从图片中的标签中提取ImageURL
NSRegularExpression *subReg = [NSRegularExpression regularExpressionWithPattern:@"http://(.*?)\"" options:0 error:NULL];
NSArray* match = [subReg matchesInString:subString options:0 range:NSMakeRange(0, [subString length] - 1)];
NSTextCheckingResult * subRes = match[0];
NSRange subRange = [subRes range];
subRange.length = subRange.length -1;
NSString * imagekUrl = [subString substringWithRange:subRange];
//将提取出的图片URL添加到图片数组中
[imageurlArray addObject:imagekUrl];
}
return imageurlArray;
}
同是天涯沦落人,祝你好运
自己加工过的一版
+ (NSArray *)filterImage:(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='"];
} else if ([imgHtml rangeOfString:@"src="].location != NSNotFound) {
tmpArray = [imgHtml componentsSeparatedByString:@"src="];
}
if (tmpArray.count >= 2) {
NSString *src = tmpArray[1];
if ([src rangeOfString:@"'"].location != NSNotFound) {
NSUInteger loc = [src rangeOfString:@"'"].location;
src = [src substringToIndex:loc];
[resultArray addObject:src];
}else if ([src rangeOfString:@"\""].location != NSNotFound){
NSUInteger loc = [src rangeOfString:@"\""].location;
src = [src substringToIndex:loc];
[resultArray addObject:src];
}else if ([src rangeOfString:@"\\s"].location != NSNotFound){
NSUInteger loc = [src rangeOfString:@"\\s"].location;
src = [src substringToIndex:loc];
[resultArray addObject:src];
}else if ([src rangeOfString:@">"].location != NSNotFound){
NSUInteger loc = [src rangeOfString:@">"].location;
src = [src substringToIndex:loc];
[resultArray addObject:src];
}
}
}
return resultArray;
}