首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在rails中用<a href=“/phrase”>短语</a>替换{短语}

在rails中用<a href=“/phrase”>短语</a>替换{短语}
EN

Stack Overflow用户
提问于 2014-03-22 06:32:45
回答 4查看 104关注 0票数 2

我想使用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>

这是针对用户生成的内容站点(格林尼治标准时间)的。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2014-03-22 07:02:42

这是简单的regexp,只需使用

代码语言:javascript
复制
your_string.gsub(/{(.*?)}/, '<a href="\\1">\\1</a>')

示例:

代码语言:javascript
复制
"{aaa} is not {bbb} you know".gsub(/{(.*?)}/, '<a href="/\\1">\\1</a>')

将产生

代码语言:javascript
复制
<a href="/aaa">aaa</a> is not <a href="/bbb">bbb</a> you know
票数 4
EN

Stack Overflow用户

发布于 2014-03-22 06:49:22

你可以用gsub做这件事。

代码语言:javascript
复制
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"
票数 1
EN

Stack Overflow用户

发布于 2014-03-22 10:37:02

一个更好的方法是使用标记输出引擎(红地毯是最健壮的)。

您必须创建一个自定义渲染器

代码语言:javascript
复制
#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")
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22574306

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档