【iOS】过滤html标签

文字(UI或分享时的标题(描述))展示给用户的时候,可能需要过滤掉html标签,有的开发团队可能把过滤操作放在后端处理,其实放在前端做相对来说比较合理(灵活性)。

那么怎样才能高效有效的过滤这些标签呢?首先想到的就是使用正则……我们我可以写一个NSString的分类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
+ (NSString *)getNormalStringFilterHTMLString:(NSString *)htmlStr{
NSString *normalStr = htmlStr.copy;
//判断字符串是否有效
if (!normalStr || normalStr.length == 0 || [normalStr isEqual:[NSNull null]]) return nil;

//过滤正常标签
NSRegularExpression *regularExpression=[NSRegularExpression regularExpressionWithPattern:@"<[^>]*>" options:NSRegularExpressionCaseInsensitive error:nil];
normalStr = [regularExpression stringByReplacingMatchesInString:normalStr options:NSMatchingReportProgress range:NSMakeRange(0, normalStr.length) withTemplate:@""];

//过滤占位符
NSRegularExpression *plExpression=[NSRegularExpression regularExpressionWithPattern:@"&[^;]+;" options:NSRegularExpressionCaseInsensitive error:nil];
normalStr = [plExpression stringByReplacingMatchesInString:normalStr options:NSMatchingReportProgress range:NSMakeRange(0, normalStr.length) withTemplate:@""];

//过滤空格
NSRegularExpression *spaceExpression=[NSRegularExpression regularExpressionWithPattern:@"^\\s*|\\s*$" options:NSRegularExpressionCaseInsensitive error:nil];
normalStr = [spaceExpression stringByReplacingMatchesInString:normalStr options:NSMatchingReportProgress range:NSMakeRange(0, normalStr.length) withTemplate:@""];

return normalStr;
}