Search code examples
htmlobjective-cparsingios6

Replace <ol> & <li> tags from html code with number in iOS 6


I am getting html code from server & I want to display it in UITextView. I need to parse the html & show plain text in UITextView. I am using below code to parse html from this post

Now I need to replace the li tag with the actual numbers . How can I do that ? e.g. Input

<ol>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

Output should be

  1. Coffee
  2. Tea
  3. Milk

Solution

  • Replace you Function with following and pass your HTML string snippet that you have posted.

    NSString *str = @"<ol>"
    "<li>Coffee</li>"
    "<li>Tea</li>"
    "<li>Milk</li>"
    "</ol>";
    
    [self stringByStrippingHTML:str];
    

    Function to replace string and Generate Desire output

    - (NSString *)stringByStrippingHTML:(NSString *)inputString
    {
        NSMutableString *outString;
    
        if (inputString)
        {
            outString = [[NSMutableString alloc] initWithString:inputString];
    
            if ([inputString length] > 0)
            {
                NSRange r;
                int index = 1;
                while ((r = [outString rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
                {
                    if([[outString substringWithRange:r] isEqualToString:@"<li>"])
                    {
                        outString = [[outString stringByReplacingCharactersInRange:r withString:[NSString stringWithFormat:@"\n %d. ",index++]] mutableCopy];
                    }
                    else
                        [outString deleteCharactersInRange:r];
                }
            }
        }
        return outString; 
    }