http://www.cnblogs.com/wupei/p/4019963.html
/**
*? 對(duì)指定內(nèi)定進(jìn)行著色捐名,keywords數(shù)組與colors數(shù)組相對(duì)應(yīng)
*
*? @param content? 全部?jī)?nèi)容
*? @param keyWords 關(guān)鍵字?jǐn)?shù)組
*? @param color??? 關(guān)鍵字對(duì)應(yīng)顏色命斧,如果傳空骄酗,則默認(rèn)對(duì)關(guān)鍵字著紅色
*? @param repeat?? 關(guān)鍵字出現(xiàn)多次的時(shí)候,是否全部進(jìn)行多次著色,默認(rèn)否
*
*? @return
*/
+(NSAttributedString*)attributeStringWithContent:(NSString*)content keyWords:(NSArray*)keyWords colors:(NSArray*)colors repeat:(BOOL)repeat;
+(NSAttributedString*)attributeStringWithContent:(NSString*)content keyWords:(NSArray*)keyWords colors:(NSArray*)colors repeat:(BOOL)repeat
{
NSMutableAttributedString*attString = [[NSMutableAttributedStringalloc] initWithString:content];
if(keyWords) {
[keyWords enumerateObjectsUsingBlock:^(idobj,NSUIntegeridx,BOOL*stop) {
NSMutableString*tmpString=[NSMutableStringstringWithString:content];
NSRangerange=[content rangeOfString:obj];
NSIntegerlocation=0;
while(range.length>0) {
UIColor *color=nil;
if(!colors[idx]) {
color=[UIColor redColor];
}else{
color=colors[idx];
}
[attString addAttribute:(NSString*)NSForegroundColorAttributeNamevalue:color range:NSMakeRange(location+range.location, range.length)];
location+=(range.location+range.length);
NSString*tmp= [tmpString substringWithRange:NSMakeRange(range.location+range.length, content.length-location)];
tmpString=[NSMutableStringstringWithString:tmp];
range=[tmp rangeOfString:obj];
if(!repeat) {
break;
}
}
}];
}
returnattString;
}
content是根據(jù)網(wǎng)址獲得的網(wǎng)頁(yè)源碼字符串
- (NSString*)changeToString:(NSString*)content{NSRegularExpression*regularExpretion=[NSRegularExpressionregularExpressionWithPattern:@"<[^>]*>|\n"options:0error:nil];? ? ? ? content = [regularExpretion stringByReplacingMatchesInString:content options:NSMatchingReportProgressrange:NSMakeRange(0, content.length) withTemplate:@"-"];//? 替換所有html和換行匹配元素為"-"regularExpretion = [NSRegularExpressionregularExpressionWithPattern:@"-{1,}"options:0error:nil] ;? ? content = [regularExpretion stringByReplacingMatchesInString:content options:NSMatchingReportProgressrange:NSMakeRange(0, content.length) withTemplate:@"-"];//? 把多個(gè)"-"匹配為一個(gè)"-"http://? 根據(jù)"-"分割到數(shù)組NSArray*arr=[NSArrayarray];? ? content = [NSStringstringWithString:content];? ? arr =? [content componentsSeparatedByString:@"-"];NSMutableArray*marr=[NSMutableArrayarrayWithArray:arr];? ? [marr removeObject:@""];NSMutableString*string = [[NSMutableStringalloc] init];for(inti =0; i < arr.count; i++) {? ? ? ? [string appendString:[NSStringstringWithFormat:@"%@",arr[i]]];? ? }returnstring;}