如何将其他内联样式应用于ruby中的html标签?

时间:2013-07-01 15:05:44

标签: ruby-on-rails ruby regex gsub

我有一个html字符串。在该字符串中,我想解析所有<p>标签并应用其他内联样式。

其他风格:style="margin:0px;padding:0px;"或者它可能是别的

情况1:

输入字符串:<p>some string</p>

输出字符串:<p style="margin:0px;padding:0px;">some string</p>

情况2:

输入字符串:<p style="text-align:right;" >some string</p>

输出字符串:<p style="text-align:right;margin:0px;padding:0px;">some string</p>

情形3:

输入字符串:<p align="justify">some string</p>

输出字符串:<p style="margin:0px;padding:0px;" align="justify">some string</p>

现在我正在使用像这样的正则表达式

myHtmlString.gsub("<p", "<p style = \"margin:0px;padding:0px\"")

除了删除以前的样式之外,哪个工作正常。我正在使用Ruby(ROR)。

我需要帮助来调整一下。

3 个答案:

答案 0 :(得分:2)

您可以使用Nokogiri在相关节点上设置[:style]来执行此操作。

require "nokogiri"

inputs = [
  '<p>some string</p>',
  '<p style="text-align:right;" >some string</p>',
  '<p align="justify">some string</p>'
]

inputs.each do |input|
  noko = Nokogiri::HTML::fragment(input)
  noko.css("p").each do |tag|
    tag[:style] = (tag[:style] || "") + "margin:0px;padding:0px;"
  end
  puts noko.to_html
end

这将循环遍历与css选择器p匹配的所有元素,并根据需要设置style属性。

输出:

<p style="margin:0px;padding:0px;">some string</p>
<p style="text-align:right;margin:0px;padding:0px;">some string</p>
<p align="justify" style="margin:0px;padding:0px;">some string</p>

答案 1 :(得分:0)

我建议不要使用正则表达式,因为正常情况下,正则表达式无法正确解析HTML。也就是说,只要您的输入数据一致,正则表达式仍然有效。您希望使用括号匹配p元素的style属性中已有的任何内容,然后将其插入替换字符串中:

myHtmlString.gsub(/<p( style="(.*)")?/,
                  "<p style=\"#{$2};margin:0px;padding:0px\"")

以下是匹配模式的工作原理:

/        #regex delimiter
<p       #match start of p tag
(        #open paren used to group, everything in this group gets saved in $1
 style=" #open style attribute
(.*)     #group contents of style attribute, gets saved to $2
"        #close style attribute
)?       #question mark makes everything in the paren group optional
/        #regex delimiter

答案 2 :(得分:0)

我最终做了这样的事情,我必须在发送电子邮件之前这样做。我知道这不是最好的方法,但值得在这里分享。 @sgroves和@Dobert给出的解决方案非常好,也很有用。

但我不想包括Nokogiri,尽管我只从上述2个解决方案中选择了这个想法。感谢。

这是我的代码(我是ROR的新手,所以在这里没什么特别的,我在HAML块中使用它)

 myString.gsub!(/<p[^>]*>/) do |match|
   match1 = match
   style1_arr = match1.scan(/style=".*"/)
   unless style1_arr.blank?
     style1 = style1_arr.first.sub("style=", "").gsub(/\"/, "").to_s
     style2 = style1 + "margin:0px;padding:0px;"
     match2 = match1.sub(/style=".*"/, "style=\"#{style2.to_s}\"")
   else
     match2 = match1.sub(/<p/, "<p style = \"margin:0px;padding:0px;\"")
   end
 end

现在myString将更新字符串。(请注意!在gsub之后)