簡體   English   中英

我正在Ruby On Rails中創建一個Twitter克隆,我如何編碼它以便'推文'中的'@ ...'變成鏈接?

[英]I am creating a Twitter clone in Ruby On Rails, how do I code it so that the '@…''s in the 'tweets' turn into links?

我有點像一個Rails新手,所以請耐心等待我,除了這一部分,我已經找到了大部分應用程序。

def linkup_mentions_and_hashtags(text)    
  text.gsub!(/@([\w]+)(\W)?/, '<a href="http://twitter.com/\1">@\1</a>\2')
  text.gsub!(/#([\w]+)(\W)?/, '<a href="http://twitter.com/search?q=%23\1">#\1</a>\2')
  text
end

我在這里找到了這個例子: http//github.com/jnunemaker/twitter-app

輔助方法的鏈接: http//github.com/jnunemaker/twitter-app/blob/master/app/helpers/statuses_helper.rb

也許您可以使用正則表達式查找“​​@ ...”然后用相應的鏈接替換匹配項?

您可以使用正則表達式來搜索@sometext {whitespace_or_endofstring}

你可以使用正則表達式,我不知道ruby,但代碼應該幾乎完全如我的例子:

Regex.Replace("this is an example @AlbertEin", 
                    "(?<type>[@#])(?<nick>\\w{1,}[^ ])", 
                    "<a href=\"http://twitter.com/${nick}\">${type}${nick}</a>");

這個例子會回來

this is an example <a href="http://twitter.com/AlbertEin>@AlbertEin</a>

如果你在.NET上運行它

正則表達式(?<type>[@#])(?<nick>\\\\w{1,}[^ ])表示捕獲並將其命名為TYPE,以@或#開頭的文本,然后捕獲並命名它NAME后面的文本包含至少一個文本字符,直到你找到一個空格。

也許您可以使用正則表達式來解析以@開頭的單詞,然后使用正確的鏈接更新該位置的字符串。

這個正則表達式將為您提供以@符號開頭的單詞,但您可能需要調整它:

\@[\S]+\

您將使用正則表達式搜索@username,然后將其轉換為相應的鏈接。

我在PHP中使用以下代碼:

$ret = preg_replace("#(^|[\n ])@([^ \"\t\n\r<]*)#ise", 
                    "'\\1<a href=\"http://www.twitter.com/\\2\" >@\\2</a>'", 
                    $ret);

我也一直在努力,我不確定它是100%完美,但它似乎工作:

  def auto_link_twitter(txt, options = {:target => "_blank"})
    txt.scan(/(^|\W|\s+)(#|@)(\w{1,25})/).each do |match|
      if match[1] == "#"
        txt.gsub!(/##{match.last}/, link_to("##{match.last}", "http://twitter.com/search/?q=##{match.last}", options))
        elsif match[1] == "@"
          txt.gsub!(/@#{match.last}/, link_to("@#{match.last}", "http://twitter.com/#{match.last}", options))
          end
    end
    txt
  end

我把它拼湊在一起谷歌搜索和一些閱讀api文檔中的String.scan。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM