开发者

Removing parts from HTML page in UIWebVIew

开发者 https://www.devze.com 2023-04-09 13:19 出处:网络
I\'m trying to remove text from html page, and I\'m using this code: NSRange *r; while ((r = [commentsOnly rangeOfString:@\"<[^>]+>\" options:NSRegularExpressionSearch]).location != NSNotFou

I'm trying to remove text from html page, and I'm using this code:

NSRange *r;
while ((r = [commentsOnly rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound) {
        commentsOnly = [commentsOnly stringByRep开发者_StackOverflow中文版lacingCharactersInRange:r withString:@""];
        NSLog(@"clearing");
    }

It removes html tags perfect, but how can I remove only one tag? For example, title or p. I don't want to remove only my tag. I want to remove start tag (<p>), info between two tags and close tag (<\p>).


If I understand your question, may be this will help you:

NSString *string = @"</body>", *htmlString = @"ddsfsdf_<body>_sdfsfd_<body>ffff</body></body>";
NSRange range = [htmlString rangeOfString:string];
if (range.location != NSNotFound)
{
    range.length += range.location;
    range.location = 0;

    string = @"<body>";
    NSRange rangeOpen = [htmlString rangeOfString:string options:NSBackwardsSearch range:range];
    if (rangeOpen.location != NSNotFound)
    {
        range.length -= rangeOpen.location;
        range.location = rangeOpen.location;
        htmlString = [htmlString stringByReplacingCharactersInRange:range withString:@""];
        NSLog(@"%@", htmlString);
    }
}


Use stringByEvaluatingJavaScriptFromString: to execute JavaScript within the UIWebView to do this. This is much less work and is also much more reliable, as it will use WebKit's HTML parser instead of naïve string replacement.

0

精彩评论

暂无评论...
验证码 换一张
取 消