iOS 过滤html标签

+ (NSString*)filterHTML:(NSString*)html {
    
    if(html.length<=0) {
        
        return@"";
        
    }
    NSString*emspStr1 =@" ";
    
    html = [html stringByReplacingOccurrencesOfString:emspStr1 withString:@"  "];

    NSString* regEx =@" ";
    
    html = [html stringByReplacingOccurrencesOfString:regEx withString:@" "];
    
    NSString* regEx1 =@"
"; html = [html stringByReplacingOccurrencesOfString:regEx1 withString:@"\n"]; NSString* regEx2 =@"
"; html = [html stringByReplacingOccurrencesOfString:regEx2 withString:@"\n"]; NSString* regEx3 =@"

"; html = [html stringByReplacingOccurrencesOfString:regEx3 withString:@"\n"]; NSRegularExpression *regularExpretion=[NSRegularExpression regularExpressionWithPattern:@"<[^>]*>|" options:0 error:nil]; html = [regularExpretion stringByReplacingMatchesInString:html options:NSMatchingReportProgress range:NSMakeRange(0, html.length) withTemplate:@""]; // NSScanner * scanner = [NSScanner scannerWithString:html]; // NSString * text = nil; // while([scanner isAtEnd]==NO) // { // //找到标签的起始位置 // [scanner scanUpToString:@"<" intoString:nil]; // //找到标签的结束位置 // [scanner scanUpToString:@">" intoString:&text]; // //替换字符 // html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""]; // } return[self flattenHTML:html]; } // 过滤后台返回字符串中的标签 + (NSString*)flattenHTML:(NSString*)html { NSScanner*theScanner; NSString*text =nil; theScanner = [NSScanner scannerWithString:html]; 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 stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>", text] withString:@"/n"]; } // MidStrTitle = html; return html; }

你可能感兴趣的:(iOS 过滤html标签)