[英]iOS: Strip <img…> from NSString (a html string)
所以我有一個NSString
,它基本上是一個包含所有常用html
元素的html
字符串。 我想做的具體事情就是從所有img
標簽中刪除它。 img
標簽可能有也可能沒有最大寬度、樣式或其他屬性,所以我不知道它們的長度。 他們總是以/>
結尾
我怎么能這樣做?
編輯:基於nicolasthenoz
的回答,我想出了一個需要更少代碼的解決方案:
NSString *HTMLTagss = @"<img[^>]*>"; //regex to remove img tag
NSString *stringWithoutImage = [htmlString stringByReplacingOccurrencesOfRegex:HTMLTagss withString:@""];
您可以將NSString
方法stringByReplacingOccurrencesOfString
與NSRegularExpressionSearch
選項一起使用:
NSString *result = [html stringByReplacingOccurrencesOfString:@"<img[^>]*>" withString:@"" options:NSCaseInsensitiveSearch | NSRegularExpressionSearch range:NSMakeRange(0, [html length])];
或者你也可以使用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:@""];
我個人的偏向這些選項在一個stringByReplacingOccurrencesOfRegex
的方法RegexKitLite
。 除非有其他一些引人注目的問題,否則沒有必要為這樣簡單的事情引入第三方庫。
使用正則表達式,找到字符串中的匹配項並刪除它們! 這是如何
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 += ([match length] - resultRange.length);
}
您可以在 Swift 4,5 中使用以下函數:
func filterImgTag(text: String) -> String{
return text.replacingOccurrences(of: "<img[^>]*>", with: "", options: String.CompareOptions.regularExpression)
}
希望能幫到大家! 如果它對你有用,請在下面評論。 謝謝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.