1

I am using the following code it just eliminating the HTML tags but does not format string. How to format as it is shown in Html.

-(NSString *)convertHTML:(NSString *)html {

    NSScanner *myScanner;
    NSString *text = nil;
    myScanner = [NSScanner scannerWithString:html];

    while ([myScanner isAtEnd] == NO) {

        [myScanner scanUpToString:@"<" intoString:NULL] ;

        [myScanner scanUpToString:@">" intoString:&text] ;

        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>", text] withString:@""];
    }
    //
    html = [html stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    return html;
}
2
  • What's exactly wrong with your code? What do you mean by "not format string"? Commented Feb 27, 2015 at 10:04
  • Ya Actually there are <br/> and <div> tags and by using the above code it removes the code. I want to change it in such a way that where <br/> tag is given it should convert it to next line in objective c Commented Feb 27, 2015 at 10:10

5 Answers 5

1

Try this one.this might be helpful

textview= [[UITextView alloc]initWithFrame:CGRectMake(10, 130, 250, 170)];
    NSString *str = [NSString stringWithFormat:@"<font color='red'>A</font><br/> shared photo of <font color='red'>B</font> with <font color='red'>C</font>, <font color='red'>D</font> "];
    [textview setValue:str forKey:@"contentToHTMLString"];
    textview.textAlignment = NSTextAlignmentLeft;
    textview.editable = NO;
    textview.font = [UIFont fontWithName:@"Verdana" size:20.0];
Sign up to request clarification or add additional context in comments.

Comments

0

i would recommend using a third party library for that like https://github.com/mwaterfall/MWFeedParser/blob/master/Classes/NSString%2BHTML.m

and than later use it like this:

NSString *string = [@"<b>Your HTML String</b>" stringByConvertingHTMLToPlainText];

3 Comments

Please provide me the link of the updated class as it is very old code and creating problem in ios8.
i see i modified it myself back than - also it needs a lot of other classes to run.
Any Other better solution because using old code with ios 8 is very incompatible.
0

There might be a better way of doing this but here is my run on this. 1. scan the html string for the html tags 2. create attributed string for each html tag 3. find all the occurrences of the tag in the string and apply the attributes to them in attributed string.

Here is my sample code to detect break and bold tag

//This method returns an array of occurrence of the tag in string
- (NSArray *)arrayOfStringFromString:(NSString *)string enclosedWithinString:(NSString *)stringOne andString:(NSString *)stringTwo{
    NSError *error = NULL;

    NSString *pattern =[NSString stringWithFormat:@"%@(.*?)%@",stringOne,stringTwo];

    NSRange range = NSMakeRange(0, string.length);

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];

    NSArray *matches = [regex matchesInString:string options:NSMatchingReportProgress range:range];

    NSMutableArray *subStringArray = [NSMutableArray array];
    [matches enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

        if ([obj isKindOfClass:[NSTextCheckingResult class]])
        {
            NSTextCheckingResult *match = (NSTextCheckingResult *)obj;
            NSRange matchRange = match.range;
            [subStringArray addObject:[string substringWithRange:matchRange]];
        }
    }];

    return subStringArray;
}

//This method returns the attributed string
- (NSMutableAttributedString*)attributedStringFromHTMLString:(NSString *)htmlString andFontSize:(float)size
{
    htmlString = [[self stringByDecodingXMLEntities:htmlString] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    NSArray *subStringArray = [self arrayOfStringFromString:htmlString enclosedWithinString:@"<b>" andString:@"</b>"];

    UIFont *lightFont = [UIFont fontWithName:@"HelveticaNeue-Light" size:size];
    UIFont *mediumFont = [UIFont fontWithName:@"HelveticaNeue-Medium" size:size];

    htmlString = [[[htmlString stringByReplacingOccurrencesOfString:@"<b>" withString:@""] stringByReplacingOccurrencesOfString:@"</b>" withString:@""] stringByReplacingOccurrencesOfString:@"<br>" withString:@"\n"];
    NSArray *otherHtmlTags = [self arrayOfStringFromString:htmlString enclosedWithinString:@"<" andString:@">"];

    for (NSString *otherHtmlString in otherHtmlTags) {
        [htmlString stringByReplacingOccurrencesOfString:otherHtmlString withString:@""];
    }
    htmlString = [htmlString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:htmlString attributes:@{NSFontAttributeName:lightFont}];
    for (NSString *string in subStringArray) {
        [attributedString addAttributes:@{NSFontAttributeName:mediumFont} range:[htmlString rangeOfString:string]];
    }
    return attributedString;
}

1 Comment

The function is quite big and 3 strings are passing please provide me the code where i just pass the html string and it is automatically give the formatted string if you can.
0
-(NSString *) stringByStrippingHTML {
  NSRange r;
  NSString *s = [[self copy] autorelease];
  while ((r = [s rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
    s = [s stringByReplacingCharactersInRange:r withString:@""];
  return s;
}

use this method its work for me

Comments

0

NSAttributedString can be initialised with HTML and will display it just fine.

If you want to remove tags, code that replaces tags in the string repeatedly runs in O (n^2), that is it will crawl for large strings. You need to have a mutable output string, and append bits to it as needed, to get linear time.

You can look for "<" and ">" characters. You then need to find which tags you have, because for some tags, everything between the start and end tag has to be deleted as well, or you end up with random rubbish.

You need to handle somehow.

And when you are done, you need to replace all & escape sequences with the correct characters.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.