从字符串中剥离HTML标记


95

如何从字符串中删除HTML标签,以便可以输出纯文本?

let str = string.stringByReplacingOccurrencesOfString("<[^>]+>", withString: "", options: .RegularExpressionSearch, range: nil)
print(str)


1
导致这个问题具有很大的价值,但按原样,由于您没有提出明确的问题,它很可能会被关闭:这是不可复制的方案。我建议您根据“ 如何提问”来改写您的问题。我不想删除该问题。
Tunaki

3
大声笑stackoverflow ...如何关闭作为“主题”?这是“ Swift remove html tags”的#1 Google搜索结果。
canhazbits 2016年

2
@canhazbits我知道是对的!单击重新打开以提名它以再次重新打开。
带领

1
Swift 3:string.replacingOccurrences(of:“ <[^>] +>”,带有:“”,选项:.regularExpression,范围:nil)
etayluz

Answers:


147

嗯,我尝试了您的功能,并在一个小例子上工作了:

var string = "<!DOCTYPE html> <html> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> </body> </html>"
let str = string.stringByReplacingOccurrencesOfString("<[^>]+>", withString: "", options: .RegularExpressionSearch, range: nil)
print(str)

//output "  My First Heading My first paragraph. "

你能举一个例子吗?

Swift 4和5版本:

var string = "<!DOCTYPE html> <html> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> </body> </html>"
let str = string.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)

25
<LOL>哈哈!</ LOL>
史蒂夫·罗森伯格


1
例如,尝试这段HTML:<p foo=">now what?">Paragraph</p>
顺磁牛角包

32
在Swift 3 string.replacingOccurrences(of: "<[^>]+>", with: "", options: String.CompareOptions.regularExpression, range: nil)
Husam

5
在Swift 4 string.replacingOccurrences(of:“ <[^>] +>”,with:“”,options:.regularExpression,range:nil)
Raegtime

29

由于HTML不是常规语言(HTML是无上下文语言),因此您不能使用正则表达式。请参阅:使用正则表达式解析HTML:为什么不呢?

我会考虑改为使用NSAttributedString。

let htmlString = "LCD Soundsystem was the musical project of producer <a href='http://www.last.fm/music/James+Murphy' class='bbcode_artist'>James Murphy</a>, co-founder of <a href='http://www.last.fm/tag/dance-punk' class='bbcode_tag' rel='tag'>dance-punk</a> label <a href='http://www.last.fm/label/DFA' class='bbcode_label'>DFA</a> 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 <a href='http://www.last.fm/tag/alternative%20dance' class='bbcode_tag' rel='tag'>alternative dance</a> and <a href='http://www.last.fm/tag/post%20punk' class='bbcode_tag' rel='tag'>post punk</a>, along with elements of <a href='http://www.last.fm/tag/disco' class='bbcode_tag' rel='tag'>disco</a> and other styles. <br />"    
let htmlStringData = htmlString.dataUsingEncoding(NSUTF8StringEncoding)!
let options: [String: AnyObject] = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding]
let attributedHTMLString = try! NSAttributedString(data: htmlStringData, options: options, documentAttributes: nil)
let string = attributedHTMLString.string

或者,正如艾尔沙德·穆罕默德(Irshad Mohamed)在评论中所做的那样:

let attributed = try NSAttributedString(data: htmlString.data(using: .unicode)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
print(attributed.string)

7
这似乎是最干净的方法,并且效果很好!最好让经过考验的Foundation框架为您处理这个问题,而不是自己编写易碎的解析器。
Shyam Bhat

4
清洁!!let attributed = try NSAttributedString(data: htmlString.data(using: .unicode)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) print(attributed.string)大多数人喜欢选择较小且易于理解的答案。
艾尔沙德·穆罕默德

1
感谢您的解决方案!在删除html标签时是否可以保存空格和换行符?当前,新字符串中不考虑所有换行符。
Astha Gupta

7
只是使用此警告:HTML样式转换(归因)缓慢!。WWDC的一名CoreText工程师告诉我,此内容不再维护,他完全忘记了。
塞伦斯

1
只是关于前一个警告的警告:让我们先看一些数据,然后再丢弃太慢的方法。您使用了大量的C库(通常没有意识到),它们不需要太多维护。那不一定是坏事。
乔尼

10

Mohamed解决方案,但作为Swift 4中的String扩展。

extension String {

    func stripOutHtml() -> String? {
        do {
            guard let data = self.data(using: .unicode) else {
                return nil
            }
            let attributed = try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
            return attributed.string
        } catch {
            return nil
        }
    }
}

8

我正在使用以下扩展程序来删除特定的HTML元素:

extension String {
    func deleteHTMLTag(tag:String) -> String {
        return self.stringByReplacingOccurrencesOfString("(?i)</?\(tag)\\b[^<]*>", withString: "", options: .RegularExpressionSearch, range: nil)
    }

    func deleteHTMLTags(tags:[String]) -> String {
        var mutableString = self
        for tag in tags {
            mutableString = mutableString.deleteHTMLTag(tag)
        }
        return mutableString
    }
}

这样就可以仅从<a>字符串中删除标签,例如:

let string = "my html <a href="">link text</a>"
let withoutHTMLString = string.deleteHTMLTag("a") // Will be "my  html link text"

@Mr Lister是否可以删除所有html标签并保留此<a href="">链接文本</a>?
Mazen Kasser


3

迅捷4:

extension String {
    func deleteHTMLTag(tag:String) -> String {
        return self.replacingOccurrences(of: "(?i)</?\(tag)\\b[^<]*>", with: "", options: .regularExpression, range: nil)
    }

    func deleteHTMLTags(tags:[String]) -> String {
        var mutableString = self
        for tag in tags {
            mutableString = mutableString.deleteHTMLTag(tag: tag)
        }
        return mutableString
    }
}

2
或者您可以这样使用:func deleteHTMLTag()->字符串{return self.replacingOccurrences(of:“(?i)</?\\ b [^ <] *>”,带有:“”,选项:.regularExpression ,范围:无)}
阿尼尔·库马尔

此正则表达式不会为我删除html代码。示例字符串:“ <b>喜欢</ b>的猫在做某事”。没有进行更多的调查,原因是它不起作用。但是text.replacingOccurrences(of:“ <[^>] +>”,....)适用于我的简单情况。
本杰明·皮耶特

2

为Swift 4更新:

guard let htmlStringData = htmlString.data(using: .unicode) else { fatalError() }

let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
                .documentType: NSAttributedString.DocumentType.html
                .characterEncoding: String.Encoding.unicode.rawValue
             ]

let attributedHTMLString = try! NSAttributedString(data: htmlStringData, options: options, documentAttributes: nil)
let string = attributedHTMLString.string

您在.documentType之后缺少“,”:param
cwgso

0

与使用NSAttributedString HTML转换相比,我更喜欢使用正则表达式,建议这样做非常耗时,并且也需要在主线程上运行。此处的更多信息:https : //developer.apple.com/documentation/foundation/nsattributedstring/1524613-initwithdata

对我来说,这就是窍门,首先我删除所有CSS内联样式,然后删除所有HTML标记。可能不像NSAttributedString选项那样可靠,但是对于我的情况来说要快得多。

extension String {
    func withoutHtmlTags() -> String {
        let str = self.replacingOccurrences(of: "<style>[^>]+</style>", with: "", options: .regularExpression, range: nil)
        return str.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.