1. 程式人生 > >iOS之載入HTML中的特殊字元

iOS之載入HTML中的特殊字元

在最近的工程中解析字串的時候出現了這樣的

這些不是標準的HTML字串 所以我們要先轉成帶<>的HTML字串 然後在進行載入

貼上程式碼

-(NSString *)filterHTML:(NSString *)html
{
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString * text = nil;
    while([scanner isAtEnd]==NO)
    {
        //找到標籤的起始位置
        [scanner scanUpToString:@"&" intoString:nil];
        //找到標籤的結束位置
        [scanner scanUpToString:@";" intoString:&text];
        //替換字元
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
    }
    //    NSString * regEx = @"<([^>]*)>";
    //    html = [html stringByReplacingOccurrencesOfString:regEx withString:@""];
    return html;
}
//將HTML字串轉化為NSAttributedString富文字字串
- (NSAttributedString *)attributedStringWithHTMLString:(NSString *)htmlString
{
    NSDictionary *options = @{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
                               NSCharacterEncodingDocumentAttribute :@(NSUTF8StringEncoding) };
    
    NSData *data = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
    
    return [[NSAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
}
//將 &lt 等類似的字元轉化為HTML中的“<”等
- (NSString *)htmlEntityDecode:(NSString *)string
{
    string = [string stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
    string = [string stringByReplacingOccurrencesOfString:@"&apos;" withString:@"'"];
    string = [string stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
    string = [string stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    string = [string stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&"]; // Do this last so that, e.g. @"&amp;lt;" goes to @"&lt;" not @"<"
    
    return string;
}


  


NSString *str = [[responseObject valueForKey:@"info"] valueForKey:@"content"];
NSLog(@"%@", str);
str = [self htmlEntityDecode:str];
NSAttributedString *attributedStr = [self attributedStringWithHTMLString:str];
contentLable.attributedText = attributedStr;
[self.webView loadHTMLString:str baseURL:nil];