简体   繁体   English

在出现之间替换字符串

[英]Replace string in between occurrences

I have a string I want to display inside the uiwebview that may look like this: 我有一个要显示在uiwebview中的字符串,该字符串可能看起来像这样:

"blah blah blah [IMG]you.png[/IMG] blah blah [IMG]me.png[/IMG]"

I want it replaced like this: 我希望将其替换为:

"blah blah blah <img src=\"you.png\"> blah blah <img src=\"me.png\">"

I can already get the string between the [IMG]...[/IMG] the problem is that it can only get the first set of [IMG]...[/IMG] and the rest of the occurrence cannot. 我已经可以在[IMG] ... [/ IMG]之间获取字符串了,问题是它只能获取第一组[IMG] ... [/ IMG],而其余的则不能。

NSRange startRange = [finalQuestionString rangeOfString:@"[IMG]"];
if (startRange.location != NSNotFound) {
     NSRange targetRange;
     targetRange.location = startRange.location + startRange.length;
     targetRange.length = [finalQuestionString length] - targetRange.location;   
     NSRange endRange = [finalQuestionString rangeOfString:@"[/IMG]" options:0 
     range:targetRange];
     if (endRange.location != NSNotFound) {
         targetRange.length = endRange.location - targetRange.location;
         NSString *imageFile = [finalQuestionString 
         substringWithRange:targetRange];//the extracted filename
     }
}

so how can I get all the occurrences of [IMG]...[/IMG] and replace it with 所以我怎样才能得到所有出现的[IMG] ... [/ IMG]并将其替换为

"<img src=\"file.png\">"

any help would be appreciated. 任何帮助,将不胜感激。 Thanks! 谢谢!

Since [IMG] will always become <img src=\\" and [/IMG] will always become \\">" , why not do something like this: 由于[IMG]将始终变为<img src=\\"[/IMG]将始终变为\\">" ,为什么不这样做:

NSString *originalString = @"blah blah blah [IMG]you.png[/IMG] blah blah [IMG]me.png[/IMG]";
NSString *tempString = [originalString stringByReplacingOccurrencesOfString:@"[IMG]" withString:@"<img src=\""];
NSString *finalString = [tempString stringByReplacingOccurrencesOfString:@"\"[/IMG]" withString:@"\'>'"];

Memory management is left as an exercise for the reader :) 内存管理留给读者练习:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM