Change HTML tags, etc. From NSString

Possible duplicate:
Remove HTML tags from NSString on iPhone

I would like to know the best method for removing all HTML / Javascript tags from NSString.

The current solution I'm using leaves comments and other tags, what would be the best way to remove them?

I know the solutions, for example. LibXML, but I would like some examples to work with.

Current solution:

- (NSString *)flattenHTML:(NSString *)html trimWhiteSpace:(BOOL)trim {

    NSScanner *theScanner;
    NSString *text = nil;

    theScanner = [NSScanner scannerWithString:html];

    while ([theScanner isAtEnd] == NO) {

        // find start of tag
        [theScanner scanUpToString:@"<" intoString:NULL] ;                 
        // find end of tag         
        [theScanner scanUpToString:@">" intoString:&text] ;

        // replace the found tag with a space
        //(you can filter multi-spaces out later if you wish)
        html = [html stringByReplacingOccurrencesOfString:
                [ NSString stringWithFormat:@"%@>", text]
                                               withString:@""];
    }

    // trim off whitespace
    return trim ? [html stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] : html;  
}
+5
source share
1 answer

Try this method to remove HTML tags from a string:

- (NSString *)stripTags:(NSString *)str
{
    NSMutableString *html = [NSMutableString stringWithCapacity:[str length]];

    NSScanner *scanner = [NSScanner scannerWithString:str];
    scanner.charactersToBeSkipped = NULL;
    NSString *tempText = nil;

    while (![scanner isAtEnd])
    {
        [scanner scanUpToString:@"<" intoString:&tempText];

        if (tempText != nil)
            [html appendString:tempText];

        [scanner scanUpToString:@">" intoString:NULL];

        if (![scanner isAtEnd])
            [scanner setScanLocation:[scanner scanLocation] + 1];

        tempText = nil;
    }

    return html;
}
+17
source

All Articles