Parsing HTML hpple replacing [element raw]

742 Views Asked by At

I'm having an issue using hpple library for parsing an HTML content.

I want to use textkit to display a good html content.

So here's my issue.

I want to replace all image or video tags with my own tag and then instert it with textkit on an UITextview.

My alogorithm :

I parse my html content on

I test with a regex if [the element raw] contains a of a with a regex

if it does, i extract the "src" of my image of video and create a personalized string

Then i want to replace the entire [element raw] with my new string

So for example :

<p>
    <img src="blablabla.jpg" />
</p>

will look like :

\IMG\blablabla.jpg

Then I remove all the HTML tags using a regex

My problem is when i want to replace the [element raw] with my new tag "\IMG\blablabla.jpg"

The regex I use

#define REGEX_IMG_CONTENT           @"<img[^>]+src=\"([^\">]+)\""
#define REGEX_IFRAME_CONTENT        @"<iframe[^>]+src=\"([^\"]+).*?</iframe>"
#define REGEX_ALL_BALISE            @"<(?:\"[^\"]*\"['\"]*|'[^']*'['\"]*|[^'\">])+>"

Initializing my custom NSTextstorage

_textStorage                   = [[HTMLTextStorage alloc]init];

NSDictionary  *attrs           = @{NSFontAttributeName:[UIFont preferredFontForTextStyle:UIFontTextStyleBody]};
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:[self.textStorage formatedHTMLStringWithString:self.post.wpContent] attributes:attrs];

Formatting my HTML String with my own tags

- (NSString *)formatedHTMLStringWithString:(NSString *)string {

    NSData   *tutorialsHtmlData         = [string dataUsingEncoding:NSUTF8StringEncoding];
    TFHpple  *tutorialsParser           = [TFHpple hppleWithHTMLData:tutorialsHtmlData];
    NSString *tutorialsXpathQueryString = @"//p";
    NSArray  *tutorialsNodes            = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString];

    for (TFHppleElement *element in tutorialsNodes) {

        NSString *imageRegexString = REGEX_IMG_CONTENT;
        NSString *videoRegexString = REGEX_IFRAME_CONTENT;

        [self formatElement:element withRegexString:imageRegexString andInitialString:string];
        [self formatElement:element withRegexString:videoRegexString andInitialString:string];
    }

    NSError *error                   = nil;
    NSRange range                    = NSMakeRange(0, string.length);
    NSString *htmlBalisesRegexString = REGEX_ALL_BALISE;
    NSRegularExpression *reg         = [NSRegularExpression regularExpressionWithPattern:htmlBalisesRegexString options:0 error:&error];
    NSString *finalString            = [reg stringByReplacingMatchesInString:string options:0 range:range withTemplate:@""];

    return finalString;
}

- (void)formatElement:(TFHppleElement *)element withRegexString:(NSString *)regexString andInitialString:(NSString *)initialString{

    NSString *raw            = [[element raw] stringByDecodingHTMLEntities];
    NSError *error           = nil;
    NSRange range            = NSMakeRange(0, raw.length);
    NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:regexString options:0 error:&error];
    NSArray *matches         = [reg matchesInString:raw options:0 range:range];

    if (matches.count != 0) {

        NSLog(@"initialString : %@",initialString);
        NSLog(@"Paragraph contains regex : %@",raw);

        NSArray *firstNode    = [element children];
        TFHppleElement *child = firstNode[0];

        if ([child hasChildren]) child = [child children][0];

        [self handleAllRegexFormatWithInitialString:initialString raw:raw child:child andRegexString:regexString];

    }
}

- (void)handleAllRegexFormatWithInitialString:(NSString *)initialString raw:(NSString *)raw child:(TFHppleElement *)child andRegexString:(NSString *)regexString {

    if ([regexString isEqualToString:REGEX_IMG_CONTENT]) initialString = [self formatedStringForChild:child withRaw:raw andInitialString:initialString andTag:@"IMG"];

    else if ([regexString isEqualToString:REGEX_IFRAME_CONTENT]) initialString = [self formatedStringForChild:child withRaw:raw andInitialString:initialString andTag:@"VIDEO"];

}

- (NSString *)formatedStringForChild:(TFHppleElement *)child withRaw:(NSString *)raw andInitialString:(NSString *)initialString andTag:(NSString *)tag {

    NSString *string                 = @"";
    NSDictionary *attributes         = [child attributes];
    NSString *replacementImageString = [NSString stringWithFormat:@"\\%@\\%@",tag,[attributes objectForKey:@"src"]];
    NSRange range                    = [initialString rangeOfString:raw];

    NSLog(@"Range : %@",NSStringFromRange(range));

    if (range.location != NSNotFound) string = [initialString stringByReplacingOccurrencesOfString:raw withString:replacementImageString];

    return string;
}

In this method, my lenght range is alway equal to 0

Here an example of what i get :

The initial html content

initialString : <p style="text-align: center;">
<a href="http://www.tuxboard.com/cet-artiste-dessine-en-negatif">
<img class="alignnone size-medium wp-image-150233" alt="dessin negatif 640x398 Cet artiste dessine en négatif" src="http://www.tuxboard.com/photos/2013/12/dessin-negatif-640x398.jpg" width="640" height="398" title="Cet artiste dessine en négatif" />
</a>
</p>
<p>
<span id="more-150230"></span><br />
Réaliser des dessins hyperréalistes, c’est déjà assez costaud, mais savoir les faire <strong>en négatif</strong> se révèle être un exploit que l’artiste malaisien <strong>Brian Lai</strong> maitrise avec perfection.</p>
<p>Voici un exemple. D’un côté, le dessin comme on le verrait à l’œil nu, de l’autre côté, quand il est passé en négatif.</p>
<p style="text-align: center;">
<a href="http://www.tuxboard.com/photos/2013/12/negatif-dessin.jpg">
<img class="alignnone size-full wp-image-150234" alt="negatif dessin Cet artiste dessine en négatif" src="http://www.tuxboard.com/photos/2013/12/negatif-dessin.jpg" width="504" height="729" title="Cet artiste dessine en négatif" />
</a>
</p>
<p style="text-align: center;">
<a href="http://www.tuxboard.com/photos/2013/12/art-negatif.jpg">
<img class="alignnone size-medium wp-image-150235" alt="art negatif 640x428 Cet artiste dessine en négatif" src="http://www.tuxboard.com/photos/2013/12/art-negatif-640x428.jpg" width="640" height="428" title="Cet artiste dessine en négatif" />
</a>
</p>
<p>Vous pensez « fake » ? Vous vous trompez. L’artiste a même réalisé une vidéo pour expliquer sa technique.</p>
<div id="tuxplayer">Chargement du player …</div>
<p><script type="text/javascript">jwplayer("tuxplayer").setup({ flashplayer: "http://medias.tuxboard.com/playerv2.swf", file: "http://medias.tuxboard.com/Brian_Lai_Invert_Drawing.mp4",image: "http://www.tuxboard.com/photos/2013/12/Video-Brian-Lai-negatif.jpg", height: 370,width: '100%', 'plugins': 'sharing-3'});</script></p>

The extracted [element raw]

2013-12-19 11:40:50.247 Tuxboard[6279:70b] Paragraph contains regex : 
<p style="text-align: center;">
<a href="http://www.tuxboard.com/cet-artiste-dessine-en-negatif">
<img class="alignnone size-medium wp-image-150233" alt="dessin negatif 640x398 Cet artiste dessine en négatif" src="http://www.tuxboard.com/photos/2013/12/dessin-negatif-640x398.jpg" width="640" height="398" title="Cet artiste dessine en négatif"/>
</a>
</p>

The range

2013-12-19 11:40:50.247 Tuxboard[6279:70b] Range : {2147483647, 0}

EDIT

I've extracted manually the part that i want my algorithm to extract and matched it with the [element raw] returned by the HTML Parser and it seems that the HTML parser remove so whitespace characters...

0

There are 0 best solutions below