Objective C HTML escape/unescape

前端 未结 14 2089
生来不讨喜
生来不讨喜 2020-11-22 16:19

Wondering if there is an easy way to do a simple HTML escape/unescape in Objective C. What I want is something like this psuedo code:

NSString *string = @\"         


        
14条回答
  •  执笔经年
    2020-11-22 16:55

    Here's a solution that neutralizes all characters (by making them all HTML encoded entities for their unicode value)... Used this for my need (making sure a string that came from the user but was placed inside of a webview couldn't have any XSS attacks):

    Interface:

    @interface NSString (escape)
    - (NSString*)stringByEncodingHTMLEntities;
    @end
    

    Implementation:

    @implementation NSString (escape)
    
    - (NSString*)stringByEncodingHTMLEntities {
        // Rather then mapping each individual entity and checking if it needs to be replaced, we simply replace every character with the hex entity
    
        NSMutableString *resultString = [NSMutableString string];
        for(int pos = 0; pos<[self length]; pos++)
            [resultString appendFormat:@"&#x%x;",[self characterAtIndex:pos]];
        return [NSString stringWithString:resultString];
    }
    
    @end
    

    Usage Example:

    UIWebView *webView = [[UIWebView alloc] init];
    NSString *userInput = @"";
    NSString *safeInput = [userInput stringByEncodingHTMLEntities];
    [webView loadHTMLString:safeInput baseURL:nil];
    

    Your mileage will vary.

提交回复
热议问题