15

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.

arielcamus
  • 773
  • 1
  • 8
  • 24
  • you are not the first with this question. Take a look at this thread: http://stackoverflow.com/questions/1105169/html-character-decoding-in-objective-c-cocoa – Shingoo Mar 02 '10 at 17:11
  • I've read that question before, but this user is asking for numeric HTML entities which are easier to replace. The numeric code is the same and you just have to replace surrounding characters. – arielcamus Mar 02 '10 at 17:49

5 Answers5

35

Check out my NSString category for HTML. Here are the methods available:

- (NSString *)stringByConvertingHTMLToPlainText;
- (NSString *)stringByDecodingHTMLEntities;
- (NSString *)stringByEncodingHTMLEntities;
- (NSString *)stringWithNewLinesAsBRs;
- (NSString *)stringByRemovingNewLinesAndWhitespace;
Michael Waterfall
  • 20,497
  • 27
  • 111
  • 168
12

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.

Matt Stevens
  • 13,093
  • 3
  • 33
  • 27
  • 1
    You don't need to comment out _GTMDevLog; you can #define it yourself to whatever you want. (Thanks to dmaclach, below.) – Reed Morse May 06 '13 at 22:52
6

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.

Prince Kumar Sharma
  • 12,591
  • 4
  • 59
  • 90
2

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.

dmaclach
  • 3,403
  • 1
  • 21
  • 23
1

Can you just use NSMutableString's replaceOccurrencesOfString:withString:options:range: method?

MarkPowell
  • 16,482
  • 7
  • 61
  • 77
  • Using this message force me to define an array with all possible strings to replace which is a very heavy work. However, I'll try to find this array in other programming language and use it in Objective-C – arielcamus Mar 02 '10 at 16:49