前言
我們在一些開發中,很有必要過濾掉用戶輸入的文本中的HTML標簽以防范XSS攻擊,本文將詳細介紹關于iOS去除html標簽的相關內容,分享出來供大家參考學習,下面話不多說了,來一起看看詳細的介紹吧。
請求接口返回的數據里包含html標簽,OC中去掉的方法之前做過,代碼如下
1
2
3
4
5
6
7
8
9
10
11
|
-(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; } |
也可以使用正則去掉
1
2
3
4
5
6
7
|
-(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; } |
還可以轉換為富文本
1
2
3
4
5
6
7
|
+ (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,來看我收集的幾種方法,其實都差不多
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
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 } } |
總結
以上就是這篇文章的全部內容了,本文還有許多不足,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:https://blog.duicode.com/2458.html