Remove HTML Tags from an NSString on the iPhone

前端 未结 22 1124
心在旅途
心在旅途 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:26

    An updated answer for @m.kocikowski that works on recent iOS versions.

    -(NSString *) stringByStrippingHTMLFromString:(NSString *)str {
    NSRange range;
    while ((range = [str rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
        str = [str stringByReplacingCharactersInRange:range withString:@""];
    return str;
    

    }

    0 讨论(0)
  • 2020-11-22 10:28
    NSAttributedString *str=[[NSAttributedString alloc] initWithData:[trimmedString dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]} documentAttributes:nil error:nil];
    
    0 讨论(0)
  • 2020-11-22 10:28

    If you want to get the content without the html tags from the web page (HTML document) , then use this code inside the UIWebViewDidfinishLoading delegate method.

      NSString *myText = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.textContent"];
    
    0 讨论(0)
  • 2020-11-22 10:31

    Here's the swift version :

    func stripHTMLFromString(string: String) -> String {
      var copy = string
      while let range = copy.rangeOfString("<[^>]+>", options: .RegularExpressionSearch) {
        copy = copy.stringByReplacingCharactersInRange(range, withString: "")
      }
      copy = copy.stringByReplacingOccurrencesOfString("&nbsp;", withString: " ")
      copy = copy.stringByReplacingOccurrencesOfString("&amp;", withString: "&")
      return copy
    }
    
    0 讨论(0)
  • 2020-11-22 10:33

    following is the accepted answer, but instead of category, it is simple helper method with string passed into it. (thank you m.kocikowski)

    -(NSString *) stringByStrippingHTML:(NSString*)originalString {
        NSRange r;
        NSString *s = [originalString copy];
        while ((r = [s rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
            s = [s stringByReplacingCharactersInRange:r withString:@""];
        return s;
    }
    
    0 讨论(0)
  • 2020-11-22 10:33

    Here's a blog post that discusses a couple of libraries available for stripping HTML http://sugarmaplesoftware.com/25/strip-html-tags/ Note the comments where others solutions are offered.

    0 讨论(0)
提交回复
热议问题