我想使用rails ( <a href="/phrase">phrase</a>文件)搜索并用<a href="/phrase">phrase</a>替换{file}的任何出现。需要替换多个短语,而且这些短语是事先不知道的。
完整的例子:
Hi {guys}, I really like {ruby on rails}
需要成为
Hi <a href="/guys">guys</a>, <a href="/ruby on rails">ruby on rails</a>
这是针对用户生成的内容站点(格林尼治标准时间)的。
发布于 2014-03-22 07:02:42
这是简单的regexp,只需使用
your_string.gsub(/{(.*?)}/, '<a href="\\1">\\1</a>')示例:
"{aaa} is not {bbb} you know".gsub(/{(.*?)}/, '<a href="/\\1">\\1</a>')将产生
<a href="/aaa">aaa</a> is not <a href="/bbb">bbb</a> you know发布于 2014-03-22 06:49:22
你可以用gsub做这件事。
irb(main):001:0> str = " I have written this phrase statement, I want to replace occurences of all phrase with other statement"
=> " I have written this phrase statement, I want to replace occurences of all phrase with other statement"
irb(main):002:0> str.gsub("phrase",'<a href="/phrase">phrase</a>')
=> " I have written this <a href=\"/phrase\">phrase</a> statement, I want to replace occurences of all <a href=\"/phrase\">phrase</a> with other statement"发布于 2014-03-22 10:37:02
一个更好的方法是使用标记输出引擎(红地毯是最健壮的)。
您必须创建一个自定义渲染器
#lib/custom_renderer.rb
class AutoLinks < Redcarpet::Render::HTML
def auto_link(phrase) #-> will need to search through content. Can research further
link_to phrase, "/#{phrase}"
end
end
#controller
markdown = Redcarpet::Markdown.new(AutoLinks, auto_link: "ruby on rails")https://stackoverflow.com/questions/22574306
复制相似问题