programing

목표 C HTML 이스케이프/에스케이프 해제

minimums 2023. 7. 27. 21:45
반응형

목표 C HTML 이스케이프/에스케이프 해제

Objective C에서 간단한 HTML 이스케이프/언 이스케이프를 할 수 있는 쉬운 방법이 있는지 궁금합니다.제가 원하는 것은 이 puedo 코드와 같은 것입니다.

NSString *string = @"<span>Foo</span>";
[string stringByUnescapingHTML];

반환되는 항목

<span>Foo</span>

다른 HTML 엔티티뿐만 아니라 ӓ와 같은 ASCII 코드도 모두 탈출하지 않기를 바랍니다.

이것을 할 수 있는 방법이 코코아 터치/UIKit에 있습니까?

XML 엔티티에 대한 내 NSString 범주를 확인하십시오.XML 엔티티(모든 HTML 문자 참조 포함)를 디코딩하고, XML 엔티티를 인코딩하고, 태그를 제거하고, 문자열에서 새 줄과 공백을 제거하는 방법이 있습니다.

- (NSString *)stringByStrippingTags;
- (NSString *)stringByDecodingXMLEntities; // Including all HTML character references
- (NSString *)stringByEncodingXMLEntities;
- (NSString *)stringWithNewLinesAsBRs;
- (NSString *)stringByRemovingNewLinesAndWhitespace;

Mac용 Google Toolbox의 다른 HTML NSString 범주
이름에도 불구하고, 이것은 iOS에서도 작동합니다.

http://google-toolbox-for-mac.googlecode.com/svn/trunk/Foundation/GTMNSString+HTML.h

/// Get a string where internal characters that are escaped for HTML are unescaped 
//
///  For example, '&amp;' becomes '&'
///  Handles &#32; and &#x32; cases as well
///
//  Returns:
//    Autoreleased NSString
//
- (NSString *)gtm_stringByUnescapingFromHTML;

저는 에 헤더, 및 프로트에헤, 구및세파포더함했습다야니해만, ▁files▁in▁header,:했다▁and▁three▁only습니 3개의 파일만 포함시켜야 했습니다.GTMDefines.h.

링크에는 아래 솔루션이 포함되어 있습니다.코코아 CF의 CFXMLCreateStringByUnescape Entities는 기능하지만 아이폰에서는 사용할 수 없습니다.

@interface MREntitiesConverter : NSObject <NSXMLParserDelegate>{
    NSMutableString* resultString;
}

@property (nonatomic, retain) NSMutableString* resultString;

- (NSString*)convertEntitiesInString:(NSString*)s;

@end


@implementation MREntitiesConverter

@synthesize resultString;

- (id)init
{
    if([super init]) {
        resultString = [[NSMutableString alloc] init];
    }
    return self;
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)s {
        [self.resultString appendString:s];
}

- (NSString*)convertEntitiesInString:(NSString*)s {
    if (!s) {
        NSLog(@"ERROR : Parameter string is nil");
    }
    NSString* xmlStr = [NSString stringWithFormat:@"<d>%@</d>", s];
    NSData *data = [xmlStr dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    NSXMLParser* xmlParse = [[[NSXMLParser alloc] initWithData:data] autorelease];
    [xmlParse setDelegate:self];
    [xmlParse parse];
    return [NSString stringWithFormat:@"%@",resultString];
}

- (void)dealloc {
    [resultString release];
    [super dealloc];
}

@end

이 솔루션은 제가 수행한 해킹된 솔루션이지만, 구문 분석에 대한 걱정 없이 단순히 문자열을 탈출하고 싶다면 다음과 같이 하십시오.

-(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;
    }

그것이 결코 우아하지 않다는 것을 알지만, 그것은 일을 완성합니다.그런 다음 다음을 호출하여 요소를 디코딩할 수 있습니다.

string = [self htmlEntityDecode:string];

제가 말했듯이, 그것은 구식이지만 효과가 있습니다.문자열을 인코딩하려면 문자열 ByReplacingOfString 매개 변수를 반대로 지정합니다.

iOS 7에서 HTML을 가져오는 NSA TributedString의 기능을 사용하여 HTML 엔티티를 NSString으로 변환할 수 있습니다.

예:

@interface NSAttributedString (HTML)
+ (instancetype)attributedStringWithHTMLString:(NSString *)htmlString;
@end

@implementation NSAttributedString (HTML)
+ (instancetype)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];
}

@end

그런 다음 엔티티를 정리할 때 코드에서 다음을 수행합니다.

NSString *cleanString = [[NSAttributedString attributedStringWithHTMLString:question.title] string];

이것이 아마도 가장 간단한 방법일 것입니다만, 저는 그것이 얼마나 성능이 좋은지 모릅니다.여러분은 "청소어떤 되어 있지 꽤나 해야 할 입니다.<img>이 메서드는 HTML에서 NSA로 변환하는 동안 해당 이미지를 다운로드하기 때문에 태그 또는 기타 유사한 것입니다.:)

다음은 모든 문자를 무력화하는 솔루션입니다(유니코드 값을 위해 모든 HTML 인코딩 엔티티로 만듦).사용자가 제공했지만 웹 뷰 내부에 배치된 문자열에 XSS 공격이 없는지 확인합니다.

인터페이스:

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

구현:

@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

사용 예:

UIWebView *webView = [[UIWebView alloc] init];
NSString *userInput = @"<script>alert('This is an XSS ATTACK!');</script>";
NSString *safeInput = [userInput stringByEncodingHTMLEntities];
[webView loadHTMLString:safeInput baseURL:nil];

마일리지는 다양합니다.

HTML 또는 XML 문자열을 인코딩하고 디코딩하는 가장 덜 침습적이고 가장 가벼운 방법은 GTMNSString을 사용하는 것입니다.HTML 에디션 코코아 포드.

인 Google NSString 도구 입니다.GTMNSString+HTML에대의존벗은을에 대한 GTMDefines.h그래서 당신이 추가해야 할 것은 1.h와 1.m입니다. 그리고 당신은 가도 좋습니다.

예:

#import "GTMNSString+HTML.h"

// Encoding a string with XML / HTML elements
NSString *stringToEncode = @"<TheBeat>Goes On</TheBeat>";
NSString *encodedString = [stringToEncode gtm_stringByEscapingForHTML];

// encodedString looks like this now:
// &lt;TheBeat&gt;Goes On&lt;/TheBeat&gt;

// Decoding a string with XML / HTML encoded elements
NSString *stringToDecode = @"&lt;TheBeat&gt;Goes On&lt;/TheBeat&gt;";
NSString *decodedString = [stringToDecode gtm_stringByUnescapingFromHTML];

// decodedString looks like this now:
// <TheBeat>Goes On</TheBeat>

다음은 사용하기 쉬운 NSString 범주 구현입니다.

완전하지는 않지만 여기에서 누락된 엔티티를 추가할 수 있습니다. http://code.google.com/p/statz/source/browse/trunk/NSString%2BHTML.m

용도:

#import "NSString+HTML.h"

NSString *raw = [NSString stringWithFormat:@"<div></div>"];
NSString *escaped = [raw htmlEscapedString];

위의 MRentityConverter는 인코더가 아닌 HTML 스트리퍼입니다.

인코더가 필요한 경우 여기로 이동하십시오. XML/HTML용 NSString 인코딩

MREnitiesConverter가 잘못된 형식의 xml을 이스케이프하는 데 사용할 수 없습니다.단순 URL에서 실패합니다.

http://www.google.com/search?client=safari&rls=en&q=fail&ie=UTF-8&oe=UTF-8

리터럴을 생성해야 하는 경우 다음과 같은 도구를 사용할 수 있습니다.

http://www.freeformatter.com/java-dotnet-escape.html#ad-output

당신을 위해 그 일을 성취하는 것.

답변을 참조하십시오.

가장 쉬운 해결책은 다음과 같이 범주를 만드는 것입니다.

카테고리의 헤더 파일은 다음과 같습니다.

#import <Foundation/Foundation.h>
@interface NSString (URLEncoding)
-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding;
@end

다음은 구현 사례입니다.

#import "NSString+URLEncoding.h"
@implementation NSString (URLEncoding)
-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
    return (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
               (CFStringRef)self,
               NULL,
               (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
               CFStringConvertNSStringEncodingToEncoding(encoding));
}
@end

이제 우리는 간단히 이것을 할 수 있습니다.

NSString *raw = @"hell & brimstone + earthly/delight";
NSString *url = [NSString stringWithFormat:@"http://example.com/example?param=%@",
            [raw urlEncodeUsingEncoding:NSUTF8Encoding]];
NSLog(url);

이 답변에 대한 크레딧은 아래 웹 사이트로 이동합니다.

http://madebymany.com/blog/url-encoding-an-nsstring-on-ios

왜 그냥 사용하지 않습니까?

NSData *data = [s dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *result = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
return result;

의심의 여지가 없지만, 제 경우에는...

이것은 제가 몇 년 전에 올린 오래된 답변입니다.제 의도는 "좋은" 그리고 "훌륭한" 해결책을 제공하는 것이 아니라, 어떤 상황에서 유용할 수 있는 "해킹" 해결책을 제공하는 것이었습니다.다른 방법이 없는 한 이 솔루션을 사용하지 마십시오.

실제로 UI WebView가 모든 작업을 수행하기 때문에 다른 답변이 제공하지 않는 많은 상황에서 완벽하게 작동합니다.그리고 자바스크립트(위험하거나 유용할 수 있음)를 주입할 수도 있습니다.공연은 끔찍해야 하지만, 사실 그렇게 나쁘지는 않습니다.

또 다른 해결책이 언급되어야 합니다.생성하기만 하면 됩니다.UIWebView인코딩된 문자열을 로드하고 텍스트를 다시 가져옵니다.태그 "<>"를 이스케이프하고 모든 html 엔티티(예: "&gt;")를 디코딩하며 다른 엔티티(예: 키릴 문자 사용)에서는 작동하지 않을 수 있습니다.최선의 해결책은 아니라고 생각합니다만, 위의 해결책이 작동하지 않으면 유용할 수 있습니다.

다음은 ARC를 사용한 작은 예입니다.

@interface YourClass() <UIWebViewDelegate>

    @property UIWebView *webView;

@end

@implementation YourClass 

- (void)someMethodWhereYouGetTheHtmlString:(NSString *)htmlString {
    self.webView = [[UIWebView alloc] init];
    NSString *htmlString = [NSString stringWithFormat:@"<html><body>%@</body></html>", self.description];
    [self.webView loadHTMLString:htmlString baseURL:nil];
    self.webView.delegate = self;
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    self.webView = nil;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    self.webView = nil;
    NSString *escapedString = [self.webView stringByEvaluatingJavaScriptFromString:@"document.body.textContent;"];
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    // Do Nothing
}

@end

언급URL : https://stackoverflow.com/questions/659602/objective-c-html-escape-unescape

반응형