Retirer les balises HTML d’une chaîne

Comment puis-je supprimer les balises HTML d’une chaîne afin de pouvoir imprimer du texte propre?

let str = ssortingng.ssortingngByReplacingOccurrencesOfSsortingng("]+>", withSsortingng: "", options: .RegularExpressionSearch, range: nil) print(str) 

Edit: Swift 3

 let str = ssortingng.replacingOccurrences(of: "]+>", with: "", options: .regularExpression, range: nil) print(str) 

Swift 4: Voir les réponses ci-dessous

Hmm, j’ai essayé votre fonction et ça a fonctionné sur un petit exemple:

 var ssortingng = "   

My First Heading

My first paragraph.

" let str = ssortingng.ssortingngByReplacingOccurrencesOfSsortingng("<[^>]+>", withSsortingng: "", options: .RegularExpressionSearch, range: nil) print(str) //output " My First Heading My first paragraph. "

Pouvez-vous donner un exemple d’un problème?

Comme HTML n’est pas un langage courant (HTML est un langage sans contexte ), vous ne pouvez pas utiliser les expressions régulières. Voir: Utiliser des expressions régulières pour parsingr le HTML: pourquoi pas?

J’envisagerais plutôt d’utiliser NSAtsortingbutedSsortingng.

 let htmlSsortingng = "LCD Soundsystem was the musical project of producer James Murphy, co-founder of  label DFA Records. Formed in 2001 in New York City, New York, United States, the music of LCD Soundsystem can also be described as a mix of  and , along with elements of  and other styles. 
" let htmlSsortingngData = htmlSsortingng.dataUsingEncoding(NSUTF8SsortingngEncoding)! let options: [Ssortingng: AnyObject] = [NSDocumentTypeDocumentAtsortingbute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAtsortingbute: NSUTF8SsortingngEncoding] let atsortingbutedHTMLSsortingng = try! NSAtsortingbutedSsortingng(data: htmlSsortingngData, options: options, documentAtsortingbutes: nil) let ssortingng = atsortingbutedHTMLSsortingng.ssortingng

J’utilise l’extension suivante pour supprimer des éléments HTML spécifiques:

 extension Ssortingng { func deleteHTMLTag(tag:Ssortingng) -> Ssortingng { return self.ssortingngByReplacingOccurrencesOfSsortingng("(?i)", withSsortingng: "", options: .RegularExpressionSearch, range: nil) } func deleteHTMLTags(tags:[Ssortingng]) -> Ssortingng { var mutableSsortingng = self for tag in tags { mutableSsortingng = mutableSsortingng.deleteHTMLTag(tag) } return mutableSsortingng } } 

Cela permet de supprimer uniquement les balises d’une chaîne, par exemple:

 let ssortingng = "my html link text" let withoutHTMLSsortingng = ssortingng.deleteHTMLTag("a") // Will be "my html link text" 

swift 4:

 extension Ssortingng { func deleteHTMLTag(tag:Ssortingng) -> Ssortingng { return self.replacingOccurrences(of: "(?i)", with: "", options: .regularExpression, range: nil) } func deleteHTMLTags(tags:[Ssortingng]) -> Ssortingng { var mutableSsortingng = self for tag in tags { mutableSsortingng = mutableSsortingng.deleteHTMLTag(tag: tag) } return mutableSsortingng } }