文字(UI或分享時(shí)的標(biāo)題(描述))展示給用戶的時(shí)候,可能需要過(guò)濾掉html標(biāo)簽徐伐,有的開(kāi)發(fā)團(tuán)隊(duì)可能把過(guò)濾操作放在后端處理明也,其實(shí)放在前端做相對(duì)來(lái)說(shuō)比較合理(靈活性)铭段。
- 那么怎樣才能高效有效的過(guò)濾這些標(biāo)簽?zāi)厍票校渴紫认氲降木褪鞘褂?strong>正則……我們我可以寫一個(gè)
NSString->Category
#pragma mark - ============== 正則去除HTML標(biāo)簽 ==============
+ (NSString *)getNormalStringFilterHTMLString:(NSString *)htmlStr{
NSString *normalStr = htmlStr.copy;
//判斷字符串是否有效
if (!normalStr || normalStr.length == 0 || [normalStr isEqual:[NSNull null]]) return nil;
//過(guò)濾正常標(biāo)簽
NSRegularExpression *regularExpression=[NSRegularExpression regularExpressionWithPattern:@"<[^>]*>" options:NSRegularExpressionCaseInsensitive error:nil];
normalStr = [regularExpression stringByReplacingMatchesInString:normalStr options:NSMatchingReportProgress range:NSMakeRange(0, normalStr.length) withTemplate:@""];
//過(guò)濾占位符
NSRegularExpression *plExpression=[NSRegularExpression regularExpressionWithPattern:@"&[^;]+;" options:NSRegularExpressionCaseInsensitive error:nil];
normalStr = [plExpression stringByReplacingMatchesInString:normalStr options:NSMatchingReportProgress range:NSMakeRange(0, normalStr.length) withTemplate:@""];
//過(guò)濾空格
NSRegularExpression *spaceExpression=[NSRegularExpression regularExpressionWithPattern:@"^\\s*|\\s*$" options:NSRegularExpressionCaseInsensitive error:nil];
normalStr = [spaceExpression stringByReplacingMatchesInString:normalStr options:NSMatchingReportProgress range:NSMakeRange(0, normalStr.length) withTemplate:@""];
return normalStr;
}
Perfect over~~