iOS实现去除html标签的方法

释放双眼,带上耳机,听听看~!

请求接口返回的数据里包含html标签,OC中去掉的方法之前做过,代码如下

-(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:@""];
}
return 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;
}

还可以转换为富文本

+ (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;
}

但是这次使用的是swift,来看我收集的几种方法,其实都差不多

func removeHTML(htmlString : String)->String{
return htmlString.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)
}
extension String {
func deleteHTMLTag(tag:String) -> String {
return self.replacingOccurrences(of: "(?i)</?(tag)\b[^<]*>", with: "", options: .regularExpression, range: nil)
}
func deleteHTMLTags(tags:[String]) -> String {
var mutableString = self
for tag in tags {
mutableString = mutableString.deleteHTMLTag(tag: tag)
}
return mutableString
}
///去掉字符串标签
mutating func filterHTML() -> String?{
let scanner = Scanner(string: self)
var text: NSString?
while !scanner.isAtEnd {
scanner.scanUpTo("<", into: nil)
scanner.scanUpTo(">", into: &text)
self = self.replacingOccurrences(of: "(text == nil ? "" : text!)>", with: "")
}
return self
}
}

 

人已赞赏
iOS文章

IOS绘制三角形

2020-2-17 11:42:16

iOS文章

iOS开发中常见的视图和图片处理

2020-2-17 13:41:51

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索