Replace string in between occurrences

喜欢而已 提交于 2019-12-12 02:09:34

问题


I have a string I want to display inside the uiwebview that may look like this:

"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.

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 src=\"file.png\">"

any help would be appreciated. Thanks!


回答1:


Since [IMG] will always become <img src=\" and [/IMG] will always become \">", why not do something like this:

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 :)



来源:https://stackoverflow.com/questions/7564725/replace-string-in-between-occurrences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!