在文本中查找URL并包装在锚标记中

时间:2012-01-25 00:39:00

标签: ruby

我基本上是在写自己的Markdown解析器。我想检测字符串中的URL,如果它是有效的URL,则用锚标记包装它。例如:

string = 'here is a link: http://google.com'
# if string matches regex (which it does)
# should return:
'here is a link: <a href="http://google.com">http://google.com</a>'

# but this would remain unchanged:
string 'here is a link: google.com'

我怎样才能做到这一点?

如果您可以指出我可以用作示例的现有Ruby markdown解析器中的代码,那么

奖励积分。

2 个答案:

答案 0 :(得分:10)

通常:使用正则表达式查找URL并将其包装在HTML中:

urls = %r{(?:https?|ftp|mailto)://\S+}i
html = str.gsub urls, '<a href="\0">\0</a>'

请注意,此特定解决方案将转为此文:

See more at http://www.google.com.

... INTO ...

See more at <a href="http://www.google.com.">http://www.google.com.</a>

所以你可能想要使用正则表达式来弄清楚URL应该在哪里结束。

答案 1 :(得分:-1)

您可以使用此jquery插件 http://www.jquery.gr/linker/