我想這已經足夠普遍了,這是一個解決的問題,但作爲一個新手用絲瓜和Nokogiri我還沒找到解決方案。從包含< and >字符的文字中剝離含有絲瓜和Nokogiri字符的HTML
我正在使用一種包裝Nokogiri的HTML清除程序庫來清理一些HTML文本以供顯示。但是,該文本有時會發生在諸如電子郵件地址等<
和>
之間的字符,例如<[email protected]>
。絲瓜絡正在考慮將其作爲HTML或XML標籤,並將其從文本中剝離。
有沒有一種方法可以防止這種情況發生,同時還能很好地清除實際的標籤?
編輯:這是一個失敗的測試案例:
require 'test/unit'
require 'test/unit/ui/console/testrunner'
require 'nokogiri'
MAGICAL_REGEXP = /<([^(?:\/|!\-\-)].*)>/
def filter_html(content)
# Current approach in a gist: We capture content enclosed in angle brackets.
# Then, we check if the excerpt right after the opening bracket is a valid HTML
# tag. If it's not, we substitute the matched content (which is the captured
# content enclosed in angle brackets) for the captured content enclosed in
# the HTML entities for the angle brackets. This does not work with nested
# HTML tags, since regular expressions are not meant for this.
content.to_s.gsub(MAGICAL_REGEXP) do |excerpt|
capture = $1
Nokogiri::HTML::ElementDescription[capture.split(/[<> ]/).first] ? excerpt : "<#{capture}>"
end
end
class HTMLTest < Test::Unit::TestCase
def setup
@raw_html = <<-EOS
<html>
<[email protected]>
<p><[email protected]<b class="highlight">bar</b>.baz></p>
<p>
<[email protected]<b class="highlight">bar</b>.baz>
</p>
< don't erase this >
</html>
EOS
@filtered_html = <<-EOS
<html>
<[email protected]>
<p><[email protected]<b class="highlight">bar</b>.baz></p>
<p>
<[email protected]<b class="highlight">bar</b>.baz>
</p>
< don't erase this >
</html>
EOS
end
def test_filter_html
assert_equal(@filtered_html, filter_html(@raw_html))
end
end
# Can you make this test pass?
Test::Unit::UI::Console::TestRunner.run(HTMLTest)
目前,我們正在使用一些非常邪惡的正則表達式兩輪牛車,試圖做到這一點,但正如上面狀態的評論,它不工作標籤「嵌套「在非標籤內部。我們實際上也想保留<b class="highlight">
元素。
下面的示例不使用絲瓜絡,但應用程序本身在其他地方,所以它不會很難在這裏添加它。我們只是不確定我們應該使用哪些配置選項,如果有的話。
該文本實際上是否包含「<」字符或是否爲「<」實體? – 2011-06-10 15:39:14
如果您提供了顯示問題的最小腳本(及其輸入和輸出),則回答起來會更容易。 – 2011-06-10 23:02:46
@ mark-thomas:我編輯了這個問題來添加一個失敗的測試用例。我希望它能夠解決這個問題。 – Bira 2011-06-13 21:14:27