搜索并替换自己的标记

时间:2014-05-14 13:11:04

标签: html ruby-on-rails string

我在Rails中有一个博客,我想在内容部分中形式化外部链接,例如跟踪点击次数,断开的链接等。

我已经开始创建自己的标记类型,我在其中使用以下内容:

block_code = [[LINK_A##URL:http://www.exampleA.com##ANCHOR:A]]
block_code = [[LINK_B##URL:http://www.exampleB.com##ANCHOR:B]]

这些字符串/标记的解释非常简单(因为我自己指定了这些字符串/标记),以便提取有关它是LINK_A还是LINK_B的信息以及URL值。我用一个函数来做这个:

render_markup(block_code) #=> "<a href='http://www.exampleA.com'>A</a>"

我现在需要做的是拥有一个迭代文本的函数,当它找到我的block_codes时,用render_markup()的结果替换它们。

example_content = "Today was a really nice day when I went to the [[LINK_A##URL:http://www.thepark.com##ANCHOR:The park]] where I had a [[LINK_B##URL:http://www.swim.com##ANCHOR:swim]] and this was very nice"

所以当我这样做时:

scan_and_replace(example_content)

它创建:

"Today was a really nice day when I went to the <a href='http://www.thepark.com'>the park</a> where I had a <a href='http://swim.com'>swim</a> and this was very nice."

每当遇到文本中的代码块时。

所以,我需要帮助的是找到并替换这些代码块,即创建scan_and_replace()函数。我不需要帮助将我的代码块渲染成HTML,这已经有效了。

如果这太难了,或者你觉得这个方法真的很糟糕(并且知道一个更好的方法可以解决同样的问题),请告诉我!

1 个答案:

答案 0 :(得分:1)

您可以使用gsub将标记替换为链接,如下所示。 这里唯一困难的部分是正则表达式/\[\[.*?##URL:(.*?)##ANCHOR:(.*?)\]\]/,这意味着搜索字符[[并将组分隔符()之间找到的所有内容分配给$ 1,将第二组中的所有内容分配给$ 2并调用渲染每场比赛的功能。

def render_markup url, anchor
  "<a href='#{url}'>#{anchor}</a>"
end

def scan_and_replace content
  content.gsub(/\[\[.*?##URL:(.*?)##ANCHOR:(.*?)\]\]/){|m| render_markup($1, $2) }
end

example_content = "Today was a really nice day when I went to the [[LINK_A##URL:http://www.thepark.com##ANCHOR:The park]] where I had a [[LINK_B##URL:http://www.swim.com##ANCHOR:swim]] and this was very nice"
puts scan_and_replace example_content

#=>Today was a really nice day when I went to the <a href='http://www.thepark.com'>The park</a> where I had a <a href='http://www.swim.com'>swim</a> and this was very nice