美文网首页
获取HTML里所有的IMG标签(返回URL地址数组)

获取HTML里所有的IMG标签(返回URL地址数组)

作者: Matte | 来源:发表于2017-02-16 10:51 被阅读139次
+ (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="];
            }
            
            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里所有的IMG标签(返回URL地址数组)

      本文链接:https://www.haomeiwen.com/subject/hwwcwttx.html