【问题标题】:Detecting if a link is internal and shorten it accordingly检测链接是否为内部链接并相应缩短链接
【发布时间】:2011-05-29 08:06:35
【问题描述】:

我一直在考虑制作一种缩短内部链接的辅助方法。例如: 如果我的网站是 example.com,并且用户发布了指向 http://www.example.com/posts/80 的链接,那么将链接文本缩短为 post#80 并将 http://www.example.com/comments/5 缩短为 comment#5 会很好。

这样就够了

url["http://www.example.com/posts/"] = "post#"

或者我应该为此使用正则表达式吗?

【问题讨论】:

    标签: ruby-on-rails ruby regex string gsub


    【解决方案1】:

    正则表达式!

    SITE_URL = 'http://www.example.com'    # make sure there is no trailing slash /
    
    url = "http://www.example.com/posts/80"
    
    short_url = url.sub( %r{^#{SITE_URL}(.*)$} , '\1')
      => "/posts/80" 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-26
      • 1970-01-01
      • 2012-02-08
      • 2015-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多