Remove HTML Tags from an NSString on the iPhone

前端 未结 22 1463
心在旅途
心在旅途 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 10:15

    I've extended the answer by m.kocikowski and tried to make it a bit more efficient by using an NSMutableString. I've also structured it for use in a static Utils class (I know a Category is probably the best design though), and removed the autorelease so it compiles in an ARC project.

    Included here in case anybody finds it useful.

    .h

    + (NSString *)stringByStrippingHTML:(NSString *)inputString;
    

    .m

    + (NSString *)stringByStrippingHTML:(NSString *)inputString 
    {
      NSMutableString *outString;
    
      if (inputString)
      {
        outString = [[NSMutableString alloc] initWithString:inputString];
    
        if ([inputString length] > 0)
        {
          NSRange r;
    
          while ((r = [outString rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
          {
            [outString deleteCharactersInRange:r];
          }      
        }
      }
    
      return outString; 
    }
    

提交回复
热议问题