是否存在类似于 HTML tidy (http://tidy.sourceforge.net/) 的库,它不是特定于操作系统的(需要在每个主机上编译)。基本上我只想验证/清理用户发送给我的 HTML。
<p>hello</p></p><br>
应该成为
<p>hello</p>
<br/>
javascript 或 ruby 中的东西对我有用。谢谢!
是否存在类似于 HTML tidy (http://tidy.sourceforge.net/) 的库,它不是特定于操作系统的(需要在每个主机上编译)。基本上我只想验证/清理用户发送给我的 HTML。
<p>hello</p></p><br>
应该成为
<p>hello</p>
<br/>
javascript 或 ruby 中的东西对我有用。谢谢!
你以前检查过这个吗?http://tidy.rubyforge.org/
在 Ruby 中,您可以在 Nokogiri 中解析 HTML,这将让您检查错误,然后让它输出 HTML,这将清除丢失的结束标记等。请注意以下 HTML 中的 title 和 p 标签未正确关闭,但 Nokogiri 添加了结束标签。
require 'nokogiri'
html = '<html><head><title>the title</head><body><p>a paragraph</body></html>'
doc = Nokogiri::HTML(html)
puts "Errors found" if (doc.errors.any?)
puts doc.to_html
# >> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
# >> <html>
# >> <head>
# >> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
# >> <title>the title</title>
# >> </head>
# >> <body><p>a paragraph</p></body>
# >> </html>
或者,您可以打开一个连接/usr/bin/tidy
并告诉它做脏活:
require 'open3'
html = '<html><head><title>the title</head><body><p>a paragraph</body></html>'
stdin, stdout, stderr = Open3.popen3('/usr/bin/tidy -qi')
stdin.puts html
stdin.close
puts stdout.read
# >> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
# >>
# >> <html>
# >> <head>
# >> <meta name="generator" content=
# >> "HTML Tidy for Mac OS X (vers 31 October 2006 - Apple Inc. build 15.3.6), see www.w3.org">
# >>
# >> <title>the title</title>
# >> </head>
# >>
# >> <body>
# >> <p>a paragraph</p>
# >> </body>
# >> </html>
html-tidy 已编译为 javascript(使用 emscripten)。
如果你足够勇敢,你可以自己将它编译成 javascript,使用你想要的选项。见https://github.com/lovasoa/tidy-html5
有一个 java 端口JTidy但我不知道其他端口,可能有某种方式可以从 Ruby 调用 HTML tidy 对你有用,prahaps 从你的 ruby webapp 命令行调用 html tidy 应用程序。
W3 验证器是否适合您?
还是您想要一些东西来修复错误?
如果您只是想要一个美化器,请使用 Pretty Diff。