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;
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With