Objective C HTML escape/unescape

前端 未结 14 2125
生来不讨喜
生来不讨喜 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 17:02

    This is an incredibly hacked together solution I did, but if you want to simply escape a string without worrying about parsing, do this:

    -(NSString *)htmlEntityDecode:(NSString *)string
        {
            string = [string stringByReplacingOccurrencesOfString:@""" withString:@"\""];
            string = [string stringByReplacingOccurrencesOfString:@"'" withString:@"'"];
            string = [string stringByReplacingOccurrencesOfString:@"<" withString:@"<"];
            string = [string stringByReplacingOccurrencesOfString:@">" withString:@">"];
            string = [string stringByReplacingOccurrencesOfString:@"&" withString:@"&"]; // Do this last so that, e.g. @"&lt;" goes to @"<" not @"<"
    
            return string;
        }
    

    I know it's by no means elegant, but it gets the job done. You can then decode an element by calling:

    string = [self htmlEntityDecode:string];
    

    Like I said, it's hacky but it works. IF you want to encode a string, just reverse the stringByReplacingOccurencesOfString parameters.

提交回复
热议问题