iOS:从NSString中删除<img rel="nofollow noreferrer" ...>(一个html字符串)

Zol*_*tók 8 html image objective-c ios

所以我有一个NSString基本上是一个html包含所有常用html元素的字符串.我想要做的具体事情是从所有img标签中剥离它.img标签可能会或可能不会有最大宽度,风格或其他属性,所以我不知道它们的长度达阵.他们总是以/>

我怎么能这样做?

编辑:基于nicolasthenoz答案,我想出了一个需要更少代码的解决方案:

NSString *HTMLTagss = @"<img[^>]*>"; //regex to remove img tag
NSString *stringWithoutImage = [htmlString stringByReplacingOccurrencesOfRegex:HTMLTagss withString:@""]; 
Run Code Online (Sandbox Code Playgroud)

Rob*_*Rob 14

您可以使用带有以下选项的NSString方法:stringByReplacingOccurrencesOfStringNSRegularExpressionSearch

NSString *result = [html stringByReplacingOccurrencesOfString:@"<img[^>]*>" withString:@"" options:NSCaseInsensitiveSearch | NSRegularExpressionSearch range:NSMakeRange(0, [html length])];
Run Code Online (Sandbox Code Playgroud)

或者你也可以使用replaceMatchesInString方法NSRegularExpression.因此,假设你有一个html NSMutableString *html,你可以:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<img[^>]*>"
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:nil];

[regex replaceMatchesInString:html
                      options:0
                        range:NSMakeRange(0, html.length)
                 withTemplate:@""];
Run Code Online (Sandbox Code Playgroud)

我个人倾向于选择其中一种选择stringByReplacingOccurrencesOfRegex方法RegexKitLite.除非有其他令人信服的问题,否则没有必要为这样简单的事情引入第三方库.