iOS解析html

首先是要对HTML文本进行去除标签。

 + (NSString *)filterHTML:(NSString *)html
{
    if (!html) {
        return nil;
    }
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString  *text = nil;
    while([scanner isAtEnd]==NO)
    {
        //找到标签的起始位置
        [scanner scanUpToString:@"<" intoString:nil];
        //找到标签的结束位置
        [scanner scanUpToString:@">" intoString:&text];
        NSRange range = [text rangeOfString:@"img"];
        if (!range.length) {
            NSRange range = [text rangeOfString:@"image"];
            if (range.length) {
                
            }else {
                //

标签设置换行 if ([text hasSuffix:@"",text] withString:@"\n"]; }else{ html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""]; } } }else { html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:[text getImageSrc]]; } } //防止设置标签导致的多次换行 NSString *n = @"\n\n"; html = [html stringByReplacingOccurrencesOfString:n withString:@"\n"]; NSString *regEx = @"""; html = [html stringByReplacingOccurrencesOfString:regEx withString:@"\""]; // NSString *nbsp= @"  "; // html = [html stringByReplacingOccurrencesOfString:nbsp withString:@"\n"]; NSString *nbsps= @" "; html = [html stringByReplacingOccurrencesOfString:nbsps withString:@" "]; NSString *amp= @"&"; html = [html stringByReplacingOccurrencesOfString:amp withString:@"&"]; return [html stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];//去除首尾空格和换行 }

然后是,用正则表达式解析字符串

/// 用正则表达式解析字符串 返回 DATKTextPart 数组
+ (NSArray *)parserString:(NSString *)text
{
   // 换行的规则
   NSString *wrapPattern = @"\n\t";
   // 表情的规则
   NSString *emotionPattern = @"\\[[0-9a-zA-Z\\u4e00-\\u9fa5]+\\]";
   // @的规则
   NSString *atPattern = @"@[0-9a-zA-Z\\u4e00-\\u9fa5]+";
   // #话题#的规则
   NSString *topicPattern = @"#[0-9a-zA-Z\\u4e00-\\u9fa5]+#";
   // url链接的规则
   //    NSString *urlPattern = @"[a-zA-z]+://[^\\s]*";//@"\\b(([\\w-]+://?|www[.])[^\\s()<>]+(?:\\([\\w\\d]+\\)|([^[:punct:]\\s]|/)))";
   NSString *urlPattern = @"((http|ftp|https)://)?(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?";
   
   
   // 中文网址匹配规则
   //    NSString *cnUrlPattern = @"((http|ftp|https|file):[^'\"\\s]+)";
   NSString *cnUrlPattern = @"((http|ftp|https|file):[^'\"]+)";
   
   // 图片链接的规则
   NSString *imgPattern = [NSString stringWithFormat:@"", cnUrlPattern];
   
   
   // 填空的规则
   NSString *gapPattern = @"_____+";
   
   // 选择填空的规则
   NSString *optionalGapPattern = @"______+";
   
   
   
   //    NSString *imgPattern = [NSString stringWithFormat:@"", @"([\\S]*)"];
   // (\\s*) 表示若干个 空格符,包括tab键和换行符
   // ([\\S]*) 匹配除去空格的任意字符
   // ([\s\S]*) 或 ([\d\D]*) 或 ([\w\W]*) 匹配包括换行符在内的任意字
   // ^s*|s*$ 匹配首尾空白字符的正则表达式 可以用来删除行首行尾的空白字符(包括空格、制表符、换页符等等),非常有用的表达式
   
   // 组合多个正则条件
   //    NSString *pattern = [NSString stringWithFormat:@"%@|%@|%@|%@|%@|%@|%@|%@", wrapPattern,emotionPattern, gapPattern,atPattern, topicPattern, urlPattern, imgPattern, optionalGapPattern];
   NSString *pattern = [NSString stringWithFormat:@"%@|%@|%@|%@|%@", wrapPattern,emotionPattern, gapPattern, imgPattern, optionalGapPattern];
   
   // 遍历所有的特殊字符串
   NSMutableArray *parts = [NSMutableArray array];
   [text enumerateStringsMatchedByRegex:pattern usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
       if ((*capturedRanges).length == 0) return;
       
       DATKTextPart *part = [[DATKTextPart alloc] init];
       part.isSpecical = YES;
       part.text = *capturedStrings;
       part.isEmotion = [part.text isMatchedByRegex:[NSString stringWithFormat:@"^%@$",emotionPattern]];//[part.text hasPrefix:@"["] && [part.text hasSuffix:@"]"];
       part.isWebsite = [part.text isMatchedByRegex:[NSString stringWithFormat:@"^%@$",urlPattern]];
       part.isTopic = [part.text isMatchedByRegex:[NSString stringWithFormat:@"^%@$",topicPattern]];
       part.isImage = [part.text isMatchedByRegex:[NSString stringWithFormat:@"^%@$",imgPattern]];
       part.isAt = [part.text isMatchedByRegex:[NSString stringWithFormat:@"^%@$",atPattern]];
       part.isGap = [part.text isMatchedByRegex:[NSString stringWithFormat:@"^%@$",gapPattern]];
       part.isOptionalGap = [part.text isMatchedByRegex:[NSString stringWithFormat:@"^%@$",optionalGapPattern]];
       
       part.isWrap = [part.text isMatchedByRegex:[NSString stringWithFormat:@"^%@$",wrapPattern]];
       part.range = *capturedRanges;
       // 二次匹配查找url
       if (part.isImage) {
           //判断是否是公式图片
           part.imgUrl = [part.text stringByMatching:cnUrlPattern capture:0];
           NSString *sizePattern = @"size='(\\d+?)-(\\d+)'";
           part.imgWidht = [[part.text stringByMatching:sizePattern capture:1] floatValue];
           part.imgHeight = [[part.text stringByMatching:sizePattern capture:2] floatValue];
           part.isFormula = [part.text containsString:@"F=1"];
       }
       [parts addObject:part];
   }];
   
   // 遍历所有的非特殊字符
   [text enumerateStringsSeparatedByRegex:pattern usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
       if ((*capturedRanges).length == 0) return;
       
       DATKTextPart *part = [[DATKTextPart alloc] init];
       part.text = *capturedStrings;
       part.range = *capturedRanges;
       [parts addObject:part];
   }];
   
   // 排序
   // 系统是按照从小 -> 大的顺序排列对象
   [parts sortUsingComparator:^NSComparisonResult(DATKTextPart *part1, DATKTextPart *part2) {
       // NSOrderedAscending = -1L, NSOrderedSame, NSOrderedDescending
       // 返回NSOrderedSame:两个一样大
       // NSOrderedAscending(升序):part2>part1
       // NSOrderedDescending(降序):part1>part2
       if (part1.range.location > part2.range.location) {
           // part1>part2
           // part1放后面, part2放前面
           return NSOrderedDescending;
       }
       // part1

这里的DATKTextPart类,主要是对正则解析出的字符串类型进行封装。方便后面使用。

typedef NS_ENUM(NSUInteger, DTKTextPartSpecicalType) {
    DTKTextPartSpecicalTypeNormal           = 0, // 无格式字符串
    DTKTextPartSpecicalTypeEmotion          = 1, // 表情
    DTKTextPartSpecicalTypeTopic            = 2, // 话题
    DTKTextPartSpecicalTypeAt               = 3, // @某人
    DTKTextPartSpecicalTypeWebsite          = 4, // 网址
    DTKTextPartSpecicalTypeImage            = 5, // 其他图片
    DTKTextPartSpecicalTypeGap              = 6, // 填空
    DTKTextPartSpecicalTypeOptionalGap      = 7, // 填空选择
    DTKTextPartSpecicalTypeWrap             = 8, // 换行
};

@interface DATKTextPart : NSObject
/** 这段文字的内容 */
@property (nonatomic, copy) NSString *text;
/** 这段文字的范围 */
@property (nonatomic, assign) NSRange range;
@property (nonatomic, assign)   DTKTextPartSpecicalType textType;

/** 是否为特殊文字 */
@property (nonatomic, assign) BOOL isSpecical;
/** 是否为表情 */
@property (nonatomic, assign) BOOL isEmotion;
/** 是否为图片 */
@property (nonatomic, assign) BOOL isImage;

/** 是否为话题 */
@property (nonatomic, assign) BOOL isTopic;
/** 是否为网址 */
@property (nonatomic, assign) BOOL isWebsite;
/** 是否为@某人 */
@property (nonatomic, assign) BOOL isAt;
/** 是否为选择填空题 */
@property (nonatomic, assign) BOOL isOptionalGap;

/** 是否为填空题 */
@property (nonatomic, assign) BOOL isGap;
/** 是否为换行 */
@property (nonatomic, assign) BOOL isWrap;

/** imgurl */
@property (nonatomic, strong) NSString *imgUrl;
/** imgWidth */
@property (nonatomic, assign) CGFloat imgWidht;
/** imgHeight */
@property (nonatomic, assign) CGFloat imgHeight;

/**
 是否是公式
 */
@property (nonatomic , assign) BOOL isFormula;

在实际项目中,我们采用第三方图文混排的TYATTributeLabel进行内容的展示和布局。
大概代码如下:

- (void)setStemContent {
    
    
    for (DATKTextPart *textPart in self.textArray) {
        if (textPart.textType == DTKTextPartSpecicalTypeNormal) {
            [self.stemLabel appendText:textPart.text];
        }
        if (textPart.textType == DTKTextPartSpecicalTypeImage) {
            
            NSURL *imageUrl = [NSURL URLWithString:textPart.imgUrl];
            // 追加 图片Url
            TYImageStorage *imageUrlStorage = [[TYImageStorage alloc]init];
            imageUrlStorage.isFormula = textPart.isFormula;
            imageUrlStorage.imageURL = imageUrl;
        
                if (imageUrlStorage.isFormula) {
                    imageUrlStorage.size = CGSizeMake(formulaImageRate*textPart.imgWidht, formulaImageRate*textPart.imgHeight);
                } else {
                    imageUrlStorage.size = CGSizeMake(normalImageRate*textPart.imgWidht, normalImageRate*textPart.imgHeight);
                }
            
            [self.stemLabel appendTextStorage:imageUrlStorage];
            [self.stemLabel appendText:@" "];
        }
        if (textPart.textType == DTKTextPartSpecicalTypeGap|| textPart.textType == DTKTextPartSpecicalTypeOptionalGap ) {
            
            // 填空题
            TYTextStorage *textStorage = [[TYTextStorage alloc] init];
            textStorage.text = @"          ";
            textStorage.underLineStyle = kCTUnderlineStyleSingle;
            textStorage.font = PF_SC_Medium(17);;
            [self.stemLabel appendTextStorage:textStorage];

        }
    }
    
    self.stemLabel.linesSpacing = tkLineSpace;
    [self.stemLabel sizeToFit];
}


你可能感兴趣的:(iOS解析html)