0

So I receive an NSString with html code like this:

<p class="img"><img src="blahblahblah"></p><p>This is some text</p>

I would like to find the end of the img-classed paragraph, so I can insert a heading in between the two paragraphs. Please note:

  • that the img-classed paragraph is not necessarily the first paragraph in the string.
  • there can be multiple img-classed paragraphs in the string but I only need to insert something after the first one

I would like to find the character-position after the first img-classed </p> in the string, and not parse it.

Zoltán Matók
  • 3,923
  • 2
  • 33
  • 64
  • Have you tried an HTML parser? See http://stackoverflow.com/questions/405749/parsing-html-on-the-iphone. – woz Nov 19 '12 at 20:36
  • Hey woz, I don't want to parse it, I just want to find that specific position within the string using some nsstring programming technique or something. – Zoltán Matók Nov 19 '12 at 20:38
  • Honestly you are going to want to parse. It is the most reliable way to find the location. – Joe Nov 19 '12 at 20:59

1 Answers1

2

You want to parse, there is really no other option. But then make sure to find a criteria which is really unique.

Here is the Cocoa+NSString solution :

            NSScanner *scanner = [NSScanner scannerWithString:originalString];


            [scanner scanUpToString:@"<p class=\"img">" intoString:nil];
            [scanner scanString:@"par_categorie_2\">" intoString:nil];

            [scanner scanUpToString:@"</p>" intoString:nil];
            [scanner scanString:@"</p>" intoString:nil];

            NSInteger insertionPoint = scanner.scanLocation;

            NSMutableString *modifiedString = [[NSMutableString alloc] initWithString:originalString];
            [modifiedString insertString:insertedString atIndex:insertionPoint];
cwehrung
  • 1,286
  • 13
  • 18