我试图对Solr搜索结果进行清理,因为其中包含html标记:
ActionController::Base.helpers.sanitize( result_string )
很容易清除突出显示的字符串,比如:I know <ul><li>ruby</li> <li>rails</li></ul>。
但是当结果突出显示时,我的内部有额外的重要标记- <em>和</em>。
I <em>know</em> <<em>ul</em>><<em>li</em>><em>ruby</em></<em>li</em>> <<em>li</em>><em>rails</em></<em>li</em>></<em>ul</em>>。
因此,当我使用嵌套的html和高亮标记对字符串进行清理时,我会得到带有htmls标记的和平号的字符串。这是不好的:)
如何清除带有<em>标记的突出显示的字符串以获得正确的结果(仅使用<em>标记的字符串)?
我找到了路,但它很慢而且不漂亮:
string = 'I <em>know</em> <<em>ul</em>><<em>li</em>><em>ruby</em></<em>li</em>> <<em>li</em>><em>rails</em></<em>li</em>></<em>ul</em>>'
['p', 'ul', 'li', 'ol', 'span', 'b', 'br'].each do |tag|
string.gsub!( "<<em>#{tag}</em>>", '' )
string.gsub!( "</<em>#{tag}</em>>", '' )
end
string = ActionController::Base.helpers.sanitize string, tags: %w(em)我如何优化它或使用更好的解决方案来完成它?编写一些正则表达式并删除html_tags,但保留<em>和</em>。
帮帮忙,谢谢。
发布于 2014-11-25 15:30:12
你可以打电话给gsub!若要丢弃所有标记,但只保留独立或不包含在html标记中的标记,请执行以下操作。
result_string.gsub!(/(<\/?[^e][^m]>)|(<<em>\w*<\/em>>)|(<\/<em>\w*<\/em>>)/, '')会起作用
解释:
# first group (<\/?[^e][^m]>)
# find all html tags that are not <em> or </em>
# second group (<<em>\w*<\/em>>)
# find all opening tags that have <em> </em> inside of them like:
# <<em>li</em>> or <<em>ul</em>>
# third group (<\/<em>\w*<\/em>>)
# find all closing tags that have <em> </em> inside of them:
# </<em>li</em>> or </<em>ul</em>>
# and gsub replaces all of this with empty string发布于 2014-11-25 12:06:37
我想你可以用苏特
Custom Use (only the mentioned tags and attributes are allowed, nothing else)
<%= sanitize @article.body, tags: %w(table tr td), attributes: %w(id class style) %>所以,像这样的东西应该能起作用:
sanitize result_string, tags: %w(em)发布于 2014-11-25 12:06:40
使用消毒的附加参数,您可以指定允许哪些标记。
在您的示例中,请尝试:
ActionController::Base.helpers.sanitize( result_string, tags: %w(em) ) 它应该能起作用
https://stackoverflow.com/questions/27125948
复制相似问题