Remove HTML Tags from an NSString on the iPhone

前端 未结 22 1179
心在旅途
心在旅途 2020-11-22 10:02

There are a couple of different ways to remove HTML tags from an NSString in Cocoa.

One way is to render the string into an

相关标签:
22条回答
  • 2020-11-22 10:38

    A quick and "dirty" (removes everything between < and >) solution, works with iOS >= 3.2:

    -(NSString *) stringByStrippingHTML {
      NSRange r;
      NSString *s = [[self copy] autorelease];
      while ((r = [s rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
        s = [s stringByReplacingCharactersInRange:r withString:@""];
      return s;
    }
    

    I have this declared as a category os NSString.

    0 讨论(0)
  • 2020-11-22 10:38

    I would imagine the safest way would just be to parse for <>s, no? Loop through the entire string, and copy anything not enclosed in <>s to a new string.

    0 讨论(0)
  • 2020-11-22 10:39

    You can use like below

    -(void)myMethod
     {
    
     NSString* htmlStr = @"<some>html</string>";
     NSString* strWithoutFormatting = [self stringByStrippingHTML:htmlStr];
    
     }
    
     -(NSString *)stringByStrippingHTML:(NSString*)str
     {
       NSRange r;
       while ((r = [str rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location     != NSNotFound)
      {
         str = [str stringByReplacingCharactersInRange:r withString:@""];
     }
      return str;
     }
    
    0 讨论(0)
  • 2020-11-22 10:39

    This is the modernization of m.kocikowski answer which removes whitespaces:

    @implementation NSString (StripXMLTags)
    
    - (NSString *)stripXMLTags
    {
        NSRange r;
        NSString *s = [self copy];
        while ((r = [s rangeOfString:@"<[^>]+>\\s*" options:NSRegularExpressionSearch]).location != NSNotFound)
            s = [s stringByReplacingCharactersInRange:r withString:@""];
        return s;
    }
    
    @end
    
    0 讨论(0)
提交回复
热议问题