从String中删除Html格式

时间:2013-02-07 16:46:16

标签: iphone ios xcode nsstring

我一直在尝试在文本视图中格式化字符串,但我无法解决它。我是xcode的新手。

我错过了这个文件中的内容吗?我一直在查看堆栈,这就是你如何做到的..但它不起作用。

enter image description here

- (NSString *)stripTags:(NSString *)str
{
    NSMutableString *html = [NSMutableString stringWithCapacity:[str length]];

    NSScanner *scanner = [NSScanner scannerWithString:str];
    scanner.charactersToBeSkipped = NULL;
    NSString *tempText = nil;

    while (![scanner isAtEnd])
    {
        [scanner scanUpToString:@"<" intoString:&tempText];

        if (tempText != nil)
            [html appendString:tempText];

        [scanner scanUpToString:@">" intoString:NULL];

        if (![scanner isAtEnd])
            [scanner setScanLocation:[scanner scanLocation] + 1];

        tempText = nil;
    }

    return html;
}


- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *str = newsArticle;

    descTextView.text = [NSString stringWithString:str];


    // Do any additional setup after loading the view from its nib.
}

3 个答案:

答案 0 :(得分:3)

此代码是此处https://stackoverflow.com/a/4886998/283412的类似问题的答案的修改版本。这将获取HTML字符串并删除格式。

-(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;
}

答案 1 :(得分:1)

您正在尝试将HTML放入标签中。您想使用UIWebView。

答案 2 :(得分:0)

@try this

-(NSString *) stringByStrippingHTML:(NSString *)HTMLString {

    NSRange r;
    while ((r = [HTMLString rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
        HTMLString = [HTMLString stringByReplacingCharactersInRange:r withString:@""];
    return HTMLString;
}