This question already has an answer here:
- Objective C HTML escape/unescape 14 answers
I'm getting text from Internet and it contains html entities (i.e. ó
= ó). I want to show this text into a custom iPhone cell.
I've tried to use a UIWebView into my custom cell but I prefer to use a multiline UILabel. The problem is I can't find any way of replacing these HTML entities.
Check out my NSString category for HTML. Here are the methods available:
- (NSString *)stringByConvertingHTMLToPlainText;
- (NSString *)stringByDecodingHTMLEntities;
- (NSString *)stringByEncodingHTMLEntities;
- (NSString *)stringWithNewLinesAsBRs;
- (NSString *)stringByRemovingNewLinesAndWhitespace;
Google Toolbox for Mac includes an iPhone-compatible NSString addition that will do this for you: gtm_stringByUnescapingFromHTML
defined in GTMNSString+HTML.h and GTMNSString+HTML.m. If you comment out the calls to _GTMDevLog and #import "GTMDefines.h" in the .m you only need to add these two files to your project.
You can make a method that can replace html entities with strings given by you.
+(NSString*)parseString:(NSString*)str
{
str = [str stringByReplacingOccurrencesOfString:@"–" withString:@"-"];
str = [str stringByReplacingOccurrencesOfString:@"”" withString:@"\""];
str = [str stringByReplacingOccurrencesOfString:@"“" withString:@"\""];
str = [str stringByReplacingOccurrencesOfString:@"ó" withString:@"o"];
str = [str stringByReplacingOccurrencesOfString:@"'" withString:@"'"];
return str;
}
call this method to replace string by sending string as parameter.
To expand on Matt Stevens answer (since I'm not allowed to comment yet), you don't need to comment out _GTMDevLog, as it is intentionally set up so that you can #define it yourself to whatever you want.
Can you just use NSMutableString
's replaceOccurrencesOfString:withString:options:range:
method?
来源:https://stackoverflow.com/questions/2364797/objective-c-how-to-replace-html-entities