Как очистить CSS-текст от HTML-строки в Swift4 - PullRequest
0 голосов
/ 18 сентября 2018

Чего я хочу добиться - я хочу очистить весь текст CSS в строке (стиль, но не HTML) из примера блока текста:

<p style="\&quot;text-align:" justify;="" \"=""><span style="\&quot;font-size:" 13px;="" font-family:="" arial;="" text-decoration-skip-ink:="" none;\"=""><b><span style="font-size: 18px;">Angkor Wat</span></b> is a temple complex in Cambodia and the largest religious monument in the world, on a site measuring 162.6 hectares (1,626,000 m2; 402 acres). It was originally constructed as a Hindu temple dedicated to the god Vishnu for the Khmer Empire, gradually transforming into a Buddhist temple towards the end of the 12th century. It was built by the Khmer King Suryavarman II in the early 12th century in Yaśodharapura, the capital of the Khmer Empire, as his state temple and eventual mausoleum. Breaking from the Shaiva tradition of previous kings, Angkor Wat was instead dedicated to Vishnu. As the best-preserved temple at the site, it is the only one to have remained a significant religious centre since its foundation. The temple is at the top of the high classical style of Khmer architecture. It has become a symbol of Cambodia, appearing on its national flag, and it is the country\'s prime attraction for visitors.</span></p>

И я нашел расширение из другого вопроса, что они могут удалить тег HTML из текста, и это расширение

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

Так, как мы можем удалить встроенный текст CSS из строки HTML?

Результат должен выглядеть следующим образом, в HTML-строке больше нет стиля

<p><span><b><span>Angkor Wat</span></b> is a temple complex in Cambodia and the largest religious monument in the world, on a site measuring 162.6 hectares (1,626,000 m2; 402 acres). It was originally constructed as a Hindu temple dedicated to the god Vishnu for the Khmer Empire, gradually transforming into a Buddhist temple towards the end of the 12th century. It was built by the Khmer King Suryavarman II in the early 12th century in Yaśodharapura, the capital of the Khmer Empire, as his state temple and eventual mausoleum. Breaking from the Shaiva tradition of previous kings, Angkor Wat was instead dedicated to Vishnu. As the best-preserved temple at the site, it is the only one to have remained a significant religious centre since its foundation. The temple is at the top of the high classical style of Khmer architecture. It has become a symbol of Cambodia, appearing on its national flag, and it is the country\'s prime attraction for visitors.</span></p>

Протестированная строка:

    let html = """
<p style="text-align: justify; "><span style="font-size: 13px; font-family: Arial; text-decoration-skip-ink: none;"><b>The Bayon</b> is a well-known and richly decorated Khmer temple at Angkor in Cambodia. Built in the late 12th or early 13th century as the official state temple of the Mahayana Buddhist King Jayavarman VII (ព្រះបាទជ័យវរ្ម័នទី ៧), the Bayon stands at the centre of Jayavarman's capital, Angkor Thom (អង្គរធំ).Following Jayavarman's death, it was modified and augmented by later Hindu and Theravada Buddhist kings in accordance with their own religious preferences.</span></p><p style="text-align: justify; "><span style="font-size: 13px; font-family: Arial; text-decoration-skip-ink: none;">The Bayon's most distinctive feature is the multitude of serene and smiling stone faces on the many towers which jut out from the upper terrace and cluster around its central peak. The temple is known also for two impressive sets of bas-reliefs, which present an unusual combination of mythological, historical, and mundane scenes. The current main conservatory body, the Japanese Government Team for the Safeguarding of Angkor (the JSA) has described the temple as "the most striking expression of the baroque style" of Khmer architecture, as contrasted with the classical style of Angkor Wat (ប្រាសាទអង្គរវត្ត).</span></p>
"""

1 Ответ

0 голосов
/ 18 сентября 2018

ОБНОВЛЕНО,

так как у вас есть новое обновление, HTML-файл которого правильно отформатирован как строка, вы можете попробовать этот код,

с использованием регулярных выражений

let regex = try! NSRegularExpression(pattern: "style=\"([^\"]*)\"", options: .caseInsensitive)
        let range = NSMakeRange(0, html.characters.count)
        let modString = regex.stringByReplacingMatches(in: html, options: [], range: range, withTemplate: "")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...