iOS实现去除html标签的方法汇总

  

  

我们在一些开发中,很有必要过滤掉用户输入的文本中的HTML标签以防范XSS攻击,本文将详细介绍关于iOS去除HTML标签的相关内容,分享出来供大家参考学习、下面话不多说了,来一起看看详细的介绍吧。

  

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

        - (NSString *) filterHTML: html (NSString *) {   NSScanner *扫描仪=[NSScanner scannerWithString: html];   NSString *文本=零;   而([扫描仪isAtEnd]==NO)   {   [扫描仪scanUpToString: @”& lt;“intoString: nil);   [扫描仪scanUpToString: @”在“intoString:和文本);   html=[html stringByReplacingOccurrencesOfString: [NSString stringWithFormat: @ % @>”,文本]withString: @ ");   }   返回html;   }      

也可以使用正则去掉

        - (NSString *) getZZwithString:字符串(NSString *) {   NSRegularExpression * regularExpretion=[NSRegularExpression regularExpressionWithPattern: @ & lt;[^祝辞]*祝辞| \ n”   选择:0   错误:nil);   字符串=[regularExpretion stringByReplacingMatchesInString:字符串选项:NSMatchingReportProgress范围:NSMakeRange (0, string.length) withTemplate: @ ");   返回字符串;   }      

还可以转换为富文本

        + (NSMutableAttributedString *) praseHtmlStr:(NSString *) htmlStr {   NSMutableAttributedString * attributedString=[[NSMutableAttributedString alloc] initWithData: [htmlStr dataUsingEncoding: NSUnicodeStringEncoding]选项:@ {NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType NSCharacterEncodingDocumentAttribute: @ (NSUTF8StringEncoding)} documentAttributes:零错误:nil);   [attributedString addAttribute: NSFontAttributeName价值:[UIFont systemFontOfSize: 13]范围:NSMakeRange (0, attributedString.length)];   [attributedString addAttribute: NSForegroundColorAttributeName值:CommonColor (Color333333)范围:NSMakeRange (0, attributedString.length)];      返回attributedString;   }      

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

        func removeHTML (htmlString:字符串)→字符串{   htmlString返回。replacingOccurrences (:“& lt;[^祝辞]+祝辞;”,:“”,选择:.regularExpression范围:nil)   }      扩展字符串{   func deleteHTMLTag(标签:字符串)→字符串{   回归自我。replacingOccurrences(的:“(& # 63;我)& lt;/& # 63; b \(标签)\ \ [^ & lt;] *祝辞;”,:“”,选择:.regularExpression范围:nil)   }      func deleteHTMLTags(标签:[String])→字符串{   var mutableString=自我   在标签标记{   mutableString=mutableString.deleteHTMLTag(标签:标签)   }   返回mutableString   }///去掉字符串标签   变异函数filterHTML ()→字符串# {63;   让扫描仪=扫描仪(字符串:自我)   var文本:nsstring # 63;   尽管!扫描仪。isAtEnd {   scanner.scanUpTo (“& lt;”,为nil):   scanner.scanUpTo(“比;”,到:和文本)   自我=自我。replacingOccurrences(:“\(文本==nil & # 63;”“:文本!)比;”,:“”)   }   回归自我   }   }      

  

以上就是这篇文章的全部内容了,本文还有许多不足,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。

iOS实现去除html标签的方法汇总