美文网首页codeER.teciOS基础知识
iOS-去掉字符串中的html标签的几种方法

iOS-去掉字符串中的html标签的几种方法

作者: 奋斗的蜗牛 | 来源:发表于2017-03-20 19:01 被阅读1607次

    方法一(单纯去除html标签):


    1. NSScanner去除标签
    -(NSString *)filterHTML:(NSString *)html
    {
        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:@""];
        }
    //    NSString * regEx = @"<([^>]*)>";
    //    html = [html stringByReplacingOccurrencesOfString:regEx withString:@""];
        return html;
    }
    

    参考链接:http://www.cnblogs.com/machealking/p/4647012.html

    • 正则去除标签
    //正则去除标签
    -(NSString *)getZZwithString:(NSString *)string{
        NSRegularExpression *regularExpretion=[NSRegularExpression regularExpressionWithPattern:@"<[^>]*>|\n"
                                                                                        options:0
                                                                                          error:nil];
        string=[regularExpretion stringByReplacingMatchesInString:string options:NSMatchingReportProgress range:NSMakeRange(0, string.length) withTemplate:@""];
        return string;
    }
    

    方法二(转化html标签为富文本):

    //转化html标签为富文本
    + (NSMutableAttributedString *)praseHtmlStr:(NSString *)htmlStr {
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithData:[htmlStr dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute :@(NSUTF8StringEncoding)} documentAttributes:nil error:nil];
        [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13] range:NSMakeRange(0, attributedString.length)];
        [attributedString addAttribute:NSForegroundColorAttributeName value:CommonColor(Color333333) range:NSMakeRange(0, attributedString.length)];
        
        return attributedString;
    }
    

    相关文章

      网友评论

        本文标题: iOS-去掉字符串中的html标签的几种方法

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