【问题标题】:How to escape anchor link content when using gsub to replace words with links使用gsub用链接替换单词时如何转义锚链接内容
【发布时间】:2012-10-25 08:45:03
【问题描述】:

我有一组单词需要用链接替换。当我的锚链接中包含一个单词时,我遇到了错误。我正在使用循环遍历所有单词,因此如果第一个链接包含要替换的当前单词,它将在现有锚标记内再次被新链接替换。

例子:

我有一句话:敏捷的棕狐跳过懒惰的狗。

我想将“Fox”替换为 <a href="#" data-content="A fox is not a dog">fox< /a>,将“Dog”替换为:<a href="#" data-content="A dog is a man's best friend">dog</a>

我的代码:

<% text = "The quick brown fox jumps over the lazy dog." %>

<% @definition.each do |d| % ><br/>
<% text = text.gsub(d.word, link_to(d.word, '# ', :class => "popover-definition", :rel => "popover", :title => "<strong>#{d.word}</strong>", :"data-content" => d.meaning)).html_safe %><br/>
<% end %>

** @definition 包含单词和替换它的链接。

当循环第二次运行时,来自 'fox' 的 &lt;a&gt; 标记中的 'dog' 被替换为新链接。当单词包含在锚点中时,如何避免字符串替换?

谢谢!

【问题讨论】:

    标签: ruby ruby-on-rails-3.1 twitter-bootstrap


    【解决方案1】:

    在 Ruby 1.9.2 及更高版本中,您可以将哈希传递给 gsub,它会将哈希中的任何键与其值匹配。

    来自documentation:

    如果第二个参数是一个哈希,匹配的文本是它的一个键,对应的值就是替换字符串。

    所以如果你首先从@definition 创建一个哈希:

    hash = @definition.inject({}) { |h, d| h[d.word] = d.meaning; h }
    #=> {"fox"=>"A fox is not a dog", "dog"=>"A dog is man's best friend"}
    

    然后你可以只用一行来替换:

    text.gsub(%r[#{hash.keys.join('|')}], hash)
    #=> "The quick brown A fox is not a dog jumps over the lazy A dog is man's best friend."
    

    只需更新hash 以使用link_to,这应该适用于您的情况:

    hash = @definition.inject({}) do |h, d|
      h[d.word] = link_to(d.word, '# ', :class => "popover-definition", :rel => "popover", :title => "<strong>#{d.word}</strong>", :"data-content" => d.meaning).html_safe
      h
    end
    text.gsub(%r[#{hash.keys.join('|')}], hash)
    

    【讨论】:

    • 很好的解决方案!我还是 RoR 的新手,很高兴我了解了哈希。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2021-04-02
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    • 1970-01-01
    • 1970-01-01
    • 2014-09-07
    相关资源
    最近更新 更多