19

CGI.escapeHTML很糟糕,但CGI.unescapeHTML完全无聊。例如:

require 'cgi'

CGI.unescapeHTML('…')
# => "…"                    # correct - an ellipsis

CGI.unescapeHTML('…')
# => "…"             # should be "…"

CGI.unescapeHTML('¢')
# => "\242"                 # correct - a cent

CGI.unescapeHTML('¢')
# => "¢"               # should be "\242"

CGI.escapeHTML("…")
# => "…"                    # should be "…"

似乎unescapeHTML知道所有的数字代码加&、、、<和。并且只知道最后四个——它不做任何数字代码。我知道转义通常不需要那么健壮,因为 HTML 将允许大多数字符的文字版本,除了知道的四个字符。但是取消转义确实应该更好。>"escapeHTMLCGI.escapeHTML

有没有更好的工具,至少可以用来逃避?

4

2 回答 2

28

htmlentities gem 应该可以解决问题:

require 'rubygems'
require 'htmlentities'

coder = HTMLEntities.new

coder.decode('…') # => "…"
coder.decode('…') # => "…"
coder.decode('¢') # => "¢"
coder.decode('¢') # => "¢"
coder.encode("…", :named) # => "…"
coder.encode("…", :decimal) # => "…"
于 2008-12-20T18:17:41.527 回答
2
require 'rubygems'
require 'hpricot'

Hpricot('…', :xhtml_strict => true).to_plain_text

尽管您可能不得不摆弄字符编码。

于 2008-12-18T23:21:06.393 回答