【问题标题】:Removing html tags and unwanted characters in iOS在 iOS 中删除 html 标签和不需要的字符
【发布时间】:2013-04-07 15:17:19
【问题描述】:

我有以下方法可以从字符串中删除 html 标签和不需要的字符:

-(NSString *) stringByStrippingHTML: (NSString*) s {
NSRange r;
while ((r = [s rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
    s = [s stringByReplacingCharactersInRange:r withString:@""];
while ((r = [s rangeOfString:@"&#8217;" options:NSRegularExpressionSearch]).location != NSNotFound)
    s = [s stringByReplacingCharactersInRange:r withString:@"\'"];
while ((r = [s rangeOfString:@"&#8221;" options:NSRegularExpressionSearch]).location != NSNotFound)
    s = [s stringByReplacingCharactersInRange:r withString:@"\""];
while ((r = [s rangeOfString:@"&#8220;" options:NSRegularExpressionSearch]).location != NSNotFound)
    s = [s stringByReplacingCharactersInRange:r withString:@"\""];
while ((r = [s rangeOfString:@"&#8230;" options:NSRegularExpressionSearch]).location != NSNotFound)
    s = [s stringByReplacingCharactersInRange:r withString:@"..."];
while ((r = [s rangeOfString:@"&#8211;" options:NSRegularExpressionSearch]).location != NSNotFound)
    s = [s stringByReplacingCharactersInRange:r withString:@"-"];

return s;
}

我有太多的while案例,如何以更优雅的方式完成?

【问题讨论】:

    标签: iphone ios objective-c xcode


    【解决方案1】:

    我相信NSString 有一些内置的方法。 Check this answer out.

    【讨论】:

    • 我可以使用其他人所做的,但我想知道目前我能做些什么。感谢您的回复!
    • 我会将您的每个案例添加到自定义字符集中,然后根据该字符集剥离字符串;而不是每个案例都有一个while循环。
    • @TylerAndFriends 字符集在这种情况下不起作用,因为应该替换的字符串由具有多个字符的序列组成。如果你想替换所有出现的&amp;#8211,你不想替换所有出现的&amp;#8等,而是所有出现这些字符的地方都以这个特定的顺序出现。
    • 我会记住这一点(并编辑我的答案),谢谢
    【解决方案2】:

    除了第一种情况,你可以像[s stringByReplacingOccurrencesOfString:"&amp;#8221;" withString:@"\""];一样使用。

    【讨论】:

      【解决方案3】:

      google-toolbox-for-mac 库(是的,这也适用于 iOS)具有一些 NSString 类别方法,可以更有效地取消转义与符号编码的字符。看看GTMNSString+HTML

      这不会处理第一种情况(剥离 HTML 标记),但对于您正在进行的其他替换,它应该是一个更快、更全面的解决方案。

      【讨论】:

      • 我试过了,但没有得到预期的不需要的字符。我不知道为什么。
      猜你喜欢
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      • 2012-09-29
      • 2013-12-16
      • 2013-10-24
      • 1970-01-01
      • 2011-02-04
      • 1970-01-01
      相关资源
      最近更新 更多