I am somewhat of a Rails newbie so bear with me, I have most of the application figured out except for this one part.
views:
468answers:
7Perhaps you could use Regular Expressions to look for "@..." and then replace the matches with the corresponding link?
You could use a regular expression to search for @sometext{whitespace_or_endofstring}
You can use regular expressions, i don't know ruby but the code should be almost exactly as my example:
Regex.Replace("this is an example @AlbertEin",
"(?<type>[@#])(?<nick>\\w{1,}[^ ])",
"<a href=\"http://twitter.com/${nick}\">${type}${nick}</a>");
This example would return
this is an example <a href="http://twitter.com/AlbertEin>@AlbertEin</a>
If you run it on .NET
The regex (?<type>[@#])(?<nick>\\w{1,}[^ ])
means, capture and name it TYPE the text that starts with @ or #, and then capture and name it NAME the text that follows that contains at least one text character until you fin a white space.
Perhaps you can use a regular expression to parse out the words starting with @
, then update the string at that location with the proper link.
This regular expression will give you words starting with @
symbols, but you might have to tweak it:
\@[\S]+\
You would use a regular expression to search for @username and then turn that to the corresponding link.
I use the following for the @ in PHP:
$ret = preg_replace("#(^|[\n ])@([^ \"\t\n\r<]*)#ise",
"'\\1<a href=\"http://www.twitter.com/\\2\" >@\\2</a>'",
$ret);
I've also been working on this, I'm not sure that it's 100% perfect, but it seems to work:
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
I pieced it together with some google searching and some reading up on String.scan in the api docs.
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
I found this example here: http://github.com/jnunemaker/twitter-app
The link to the helper method: http://github.com/jnunemaker/twitter-app/blob/master/app/helpers/statuses_helper.rb