2012-09-19 6 views
8

Así que tienen un NSString que es básicamente una cadena html con todos los habituales html elementos. Lo específico que me gustaría hacer es para simplemente quitarlo de todas las etiquetas img. Las etiquetas img pueden tener o no ancho máximo, estilo u otros atributos, por lo que no conozco su longitud por adelantado. Siempre terminan con />iOS: Gaza <img...> de NSString (una cadena html)

¿Cómo puedo hacer esto?

EDIT: Basado en nicolasthenoz 's respuesta, se me ocurrió una solución que requiere menos código:

NSString *HTMLTagss = @"<img[^>]*>"; //regex to remove img tag 
NSString *stringWithoutImage = [htmlString stringByReplacingOccurrencesOfRegex:HTMLTagss withString:@""]; 

Respuesta

14

Puede utilizar el método NSStringstringByReplacingOccurrencesOfString con la opción NSRegularExpressionSearch:

NSString *result = [html stringByReplacingOccurrencesOfString:@"<img[^>]*>" withString:@"" options:NSCaseInsensitiveSearch | NSRegularExpressionSearch range:NSMakeRange(0, [html length])]; 

O también se puede utilizar el método de NSRegularExpressionreplaceMatchesInString. Por lo tanto, suponiendo que tiene su html en un NSMutableString *html, puede:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<img[^>]*>" 
                     options:NSRegularExpressionCaseInsensitive 
                     error:nil]; 

[regex replaceMatchesInString:html 
         options:0 
         range:NSMakeRange(0, html.length) 
       withTemplate:@""]; 

personalmente me inclino por una de estas opciones con respecto al método de RegexKitLitestringByReplacingOccurrencesOfRegex. No es necesario introducir una biblioteca de terceros para algo tan simple como esto, a menos que haya algún otro problema importante.

+0

Gracias, no había visto eso antes y es mucho más simple ... – nicolasthenoz

+0

Tiene sentido, gracias! –

3

utilizar una expresión regular, encontrar los matchs en su cadena y eliminarlos! Aquí es cómo

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<img[^>]*>" 
                     options:NSRegularExpressionCaseInsensitive 
                     error:nil]; 

NSMutableString* mutableString = [yourStringToStripFrom mutableCopy]; 
NSInteger offset = 0; // keeps track of range changes in the string due to replacements. 
for (NSTextCheckingResult* result in [regex matchesInString:yourStringToStripFrom 
                options:0 
                 range:NSMakeRange(0, [yourStringToStripFrom length])]) { 

    NSRange resultRange = [result range]; 
    resultRange.location += offset; 

    NSString* match = [regex replacementStringForResult:result 
               inString:mutableString 
               offset:offset 
               template:@"$0"]; 

    // make the replacement 
    [mutableString replaceCharactersInRange:resultRange withString:@""]; 

    // update the offset based on the replacement 
    offset += ([replacement length] - resultRange.length); 
} 
+0

No entiendo muy bien por qué necesitarías todo este código en el ciclo for. ¿Podría explicar la diferencia entre su solución y la mía? (Editado la pregunta) –

Cuestiones relacionadas