在某些場(chǎng)景會(huì)遇到需要將網(wǎng)頁文本解析為字符串并保留格式的問題,下面列舉OC/swift的解析方法
OC
缺少P標(biāo)簽的解析,參考swift
-(NSString*)html5CodeToString {
? ? NSString *str = [self stringByReplacingOccurrencesOfString:@"<" withString:@"<"];
? ? str = [strstringByReplacingOccurrencesOfString:@">" withString:@">"];
? ? str = [strstringByReplacingOccurrencesOfString:@"&" withString:@"&"];
? ? str = [strstringByReplacingOccurrencesOfString:@""" withString:@"“"];
? ? str = [strstringByReplacingOccurrencesOfString:@"®" withString:@"?"];
? ? str = [strstringByReplacingOccurrencesOfString:@"©" withString:@"?"];
? ? str = [strstringByReplacingOccurrencesOfString:@"™" withString:@"?"];
? ? str = [strstringByReplacingOccurrencesOfString:@" " withString:@" "];
? ? str = [strstringByReplacingOccurrencesOfString:@" " withString:@" "];
? ? str = [strstringByReplacingOccurrencesOfString:@" " withString:@" "];
? ? returnstr;
}
swift
extension String {
? ? funchtml5CodeToString() ->String{
? ? ? ? varstr =self.replacingOccurrences(of:"<", with:"<")
? ? ? ? str = str.replacingOccurrences(of:">", with:">")
? ? ? ? str = str.replacingOccurrences(of:"&", with:"&")
? ? ? ? str = str.replacingOccurrences(of:""", with:"“<”")
? ? ? ? str = str.replacingOccurrences(of:"®", with:"?")
? ? ? ? str = str.replacingOccurrences(of:"©", with:"?")
? ? ? ? str = str.replacingOccurrences(of:"™", with:"?")
? ? ? ? str = str.replacingOccurrences(of:" ", with:" ")
? ? ? ? str = str.replacingOccurrences(of:" ", with:" ")
? ? ? ? str = str.replacingOccurrences(of:" ", with:" ")
? ? ? ? str = str.replacingOccurrences(of:"<p>", with:"")
? ? ? ? str = str.replacingOccurrences(of:"</p>", with:"\n")
? ? ? ? returnstr
? ? }
}