使用 ruby (不是 Rails),我试图弄清楚如何用字符串替换(而不是追加)静态文件中的某个块。例如,在 static_file.html 中,我想替换 html 注释“start”和“end”之间的所有内容:
<p>lorem ipsum blah blah ipsum</p>
<!--start-->
REPLACE MULTI-LINE
CONTENT HERE...
<!--end-->
<p>other stuff still here...</p>
一些答案在这里 https://stackoverflow.com/questions/2139058/how-to-insert-a-string-into-a-textfile有助于在某个位置插入文本,但不能处理之间的情况。
这是一个为您处理它的函数。只需向其传递一个文件路径和要在这些 HTML 注释块之间替换的内容:
只要您的注释块的格式始终相同: 和 ,就可以了。
def replace(file_path, contents)
file = File.open(file_path, "r+")
html = ""
while(!file.eof?)
html += file.readline
end
file.close()
return html.gsub(/<!--start-->(.*)<!--end-->/im, contents)
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)