Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip out HTML Tags etc from NSString [duplicate]

Possible Duplicate:
Remove HTML Tags from an NSString on the iPhone

I would like to know the best method for stripping out all HTML/Javascript etc tags out of an NSString.

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

I know OF solutions e.g. 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;  
}
like image 465
nhunston Avatar asked May 29 '11 21:05

nhunston


1 Answers

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;
}
like image 132
Dee Avatar answered Oct 05 '22 11:10

Dee