【问题标题】:Strip out HTML Tags etc from NSString [duplicate]从 NSString 中删除 HTML 标签等 [重复]
【发布时间】:2011-09-04 11:01:56
【问题描述】:

可能重复:
Remove HTML Tags from an NSString on the iPhone

我想知道从 NSString 中去除所有 HTML/Javascript 等标签的最佳方法。

我当前使用的解决方案会留下 cmets 和其他标签,删除它们的最佳方法是什么?

我知道 OF 解决方案,例如LibXML,但我想要一些可以使用的示例。

目前的解决方案:

- (NSString *)flattenHTML:(NSString *)html trimWhiteSpace:(BOOL)trim {

    NSScanner *theScanner;
    NSString *text = nil;

    theScanner = [NSScanner scannerWithString:html];

    while ([theScanner isAtEnd] == NO) {

        // find start of tag
        [theScanner scanUpToString:@"<" intoString:NULL] ;                 
        // find end of tag         
        [theScanner scanUpToString:@">" intoString:&text] ;

        // replace the found tag with a space
        //(you can filter multi-spaces out later if you wish)
        html = [html stringByReplacingOccurrencesOfString:
                [ NSString stringWithFormat:@"%@>", text]
                                               withString:@""];
    }

    // trim off whitespace
    return trim ? [html stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] : html;  
}

【问题讨论】:

  • @x3ro 所以投票将其作为副本关闭
  • @Mark He 做到了,当有人投票结束时,该评论会自动添加(为了发帖者的利益)。
  • 嗯,当我看到它时,关闭计数仍然为零
  • @Mark:我会的,但我看不到“关闭”链接:)

标签: iphone objective-c


【解决方案1】:

试试这个方法从字符串中删除 HTML 标记:

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

【讨论】:

  • 我在上面的代码中添加了scanner.charactersToBeSkipped = NULL 以避免单词粘连,如下所述:stackoverflow.com/questions/2828737/…
  • 除了许多人为的情况外,“我的字符串带有
  • 只有在某些情况下才能正确编码。例如。 Then x &lt; 12 then y &gt; 10 我们将收到Then x 10
  • 我正在寻找一种可以从 HTML 字符串中去除 &lt;source srcset&gt; 标记的方法,这非常有效,谢谢!
猜你喜欢
  • 2012-12-29
  • 2018-06-21
  • 2014-07-08
  • 2010-11-10
  • 2012-12-06
  • 1970-01-01
  • 1970-01-01
  • 2019-05-01
相关资源
最近更新 更多