NSString with some html tags, how can I search for <img> tag and get the content of url

StackOverflow https://stackoverflow.com/questions/6310773

سؤال

I have a NSString with some html tags, how can I search for tag and get the content of url? I'm not sure if I must use Hpple or a simple Regex expression. In both cases can I have some example?

هل كانت مفيدة؟

المحلول

One way to do this is using NSScanner. See this example:

NSString *url = nil;
NSString *htmlString = ...
NSScanner *theScanner = [NSScanner scannerWithString:htmlString];
// find start of IMG tag
[theScanner scanUpToString:@"<img" intoString:nil];
if (![theScanner isAtEnd]) {
    [theScanner scanUpToString:@"src" intoString:nil];
    NSCharacterSet *charset = [NSCharacterSet characterSetWithCharactersInString:@"\"'"];
    [theScanner scanUpToCharactersFromSet:charset intoString:nil];
    [theScanner scanCharactersFromSet:charset intoString:nil];
    [theScanner scanUpToCharactersFromSet:charset intoString:&url];
    // "url" now contains the URL of the img
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top