我有一个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)。
我需要帮助来调整一下。
答案 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之后)