My problem is finding the position of a specific word (ex: span) in an NSString containing html text, and replace this word.
For example, if my target word is span, my replacement text should look like:
<SPAN style="BACKGROUND-COLOR: #FF0000">span</SPAN>
If my starting text is:
<span class='i_04_12_000000'>this is a span</span>
My desired result would be:
<span class='i_04_12_000000'>this is a <SPAN style="BACKGROUND-COLOR: #FF0000">span</SPAN></span>
Obviously if I just search for span I won't find just the occurrence inside the html tag. Ideas on how to locate the correct string, even with a NSRange ?
UPDATE:
This is the final solution: ;)
+(NSString *)emphasizeString:(NSString *)stringToEmphasize inText:(NSString *)fullText
{
NSString * regExp = [NSString stringWithFormat:@"(?i)([\\s\\.,>'-])(%@)([\\s\\.,;!\\?\\)<])",stringToEmphasize];;
NSArray * regexResult = [fullText arrayOfCaptureComponentsMatchedByRegex:regExp];
NSString * result = [NSString stringWithString:fullText];
if([regexResult count] >0)
{
for (NSArray * match in regexResult)
{
NSString * all = [match objectAtIndex:0];
NSString * before = [match objectAtIndex:1];
NSString * matched = [match objectAtIndex:2];
NSString * after = [match objectAtIndex:3];
result = [result stringByReplacingOccurrencesOfString:all
withString:[NSString stringWithFormat:@"%@<SPAN style=\"BACKGROUND-COLOR: #FF0000\">%@</SPAN>%@",before, matched, after]
options:NSCaseInsensitiveSearch
range: [result rangeOfString:all]];
}
}
NSLog(@"%@",result);
return result;
}
<span>?