IOS: Strip <img ...> from NSString (html string)

So, I have an NSString , which is basically an html string with all the usual html elements. The specific thing I would like to do is simply remove it from all img tags. img tags may or may not have a maximum width, style, or other attributes, so I don’t know their length in front. They always end in />

How can i do this?

EDIT: Based on nicolasthenoz answer nicolasthenoz I came up with a solution requiring less code:

 NSString *HTMLTagss = @"<img[^>]*>"; //regex to remove img tag NSString *stringWithoutImage = [htmlString stringByReplacingOccurrencesOfRegex:HTMLTagss withString:@""]; 
+8
html ios objective-c image
source share
2 answers

You can use the NSString method stringByReplacingOccurrencesOfString with the NSRegularExpressionSearch option:

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

Or you can also use the replaceMatchesInString method of the NSRegularExpression . Thus, assuming you have html in NSMutableString *html , you can:

 NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<img[^>]*>" options:NSRegularExpressionCaseInsensitive error:nil]; [regex replaceMatchesInString:html options:0 range:NSMakeRange(0, html.length) withTemplate:@""]; 

I personally tend to one of these options using the stringByReplacingOccurrencesOfRegex RegexKitLite method. There is no need to introduce a third-party library for something as simple as this, unless there was some other compelling problem.

+14
source share

Use regex, find matches in your string and delete them! Here is how

 NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<img[^>]*>" options:NSRegularExpressionCaseInsensitive error:nil]; NSMutableString* mutableString = [yourStringToStripFrom mutableCopy]; NSInteger offset = 0; // keeps track of range changes in the string due to replacements. for (NSTextCheckingResult* result in [regex matchesInString:yourStringToStripFrom options:0 range:NSMakeRange(0, [yourStringToStripFrom length])]) { NSRange resultRange = [result range]; resultRange.location += offset; NSString* match = [regex replacementStringForResult:result inString:mutableString offset:offset template:@"$0"]; // make the replacement [mutableString replaceCharactersInRange:resultRange withString:@""]; // update the offset based on the replacement offset += ([replacement length] - resultRange.length); } 
+3
source share

All Articles