Quantcast
Channel: Developer Feed - Snippet
Viewing all articles
Browse latest Browse all 178

How to remove HTML tags from a String in iOS?

$
0
0

Sprite Fading Effects

Say you are scraping a feed or a page or parsing RSS feed, and the content that you are interested in say Title has some html elements in it (normally is an image) but you want to strip out the html elements and just display the text(making it more readable). In such cases the below snippet helps to strip out any HTML tags and replace them with a space comes to rescue. It basically uses NSScanner to scan to find the beginning of the html tag < till it find the end of the tag >, then it replaces the inner text with a space.

<!--break-->

Code Snippet

The following code snippet shows the main methods.

  1. +(NSString*)flattenHtml:(NSString*) html {
  2.         NSScanner*theScanner;
  3.         NSString*text =nil;
  4.  
  5.         theScanner =[NSScanner scannerWithString: html];
  6.  
  7.         while([theScanner isAtEnd]==NO){
  8.                 // find start of tag
  9.                 [theScanner scanUpToString:@"<" intoString:NULL];
  10.  
  11.                 // find end of tag
  12.                 [theScanner scanUpToString:@">" intoString:&text];
  13.  
  14.                 // replace the found tag with a space
  15.                 //(you can filter multi-spaces out later if you wish)
  16.                 html =[html stringByReplacingOccurrencesOfString:
  17.                         [NSString stringWithFormat:@"%@>", text]
  18.                         withString:@" "];
  19.         }// while //
  20.  
  21.         return html;
  22. }

Viewing all articles
Browse latest Browse all 178

Trending Articles