开发者

Making a link from a string

I am using Ruby on Rails 3 and I would like to extract from a string the first URL or e-mail address and then us开发者_如何学Goe the resulting string (examples: "http://www.test.com", "mailto:test@test.com", ...) as the href attribute value used in a HTML <a href="resulting_string_value">Test link name</a>.

How can I do that in the safest way?

P.S.: I know the RoR auto_link method, but that does not accomplish what I need.


Domain and host names can have - or . characters in them and email usernames have a system-specific definition. Here is a hURL matcher that tries to share the DNS parse.

/((https*\:\/\/)|(mailto:[^@]+@))(\/*[\w\-rb.]+)*/


Ok, you probably didn't want a regular expression, but it works, and you might use it as a helper

The code for urls:

str = "http://someurl.com/"
str.scan(/http:\/\/([^\/]*)/)

The code for emails:

str = "mailto:someemail@email.com"
str.scan(/mailto:([^ ]*)/)

Putting it all together:

result_array = str.scan(/mailto:([^ ]*)|http:\/\/([^\/]*)/)
if result_array.length > 0
  result = result[0][0] unless empty? result[0][0] 
  result = result[0][1] unless empty? result[0][1] 
end


If you just want the first link in the string, you can just use match. Also, you want to use a non-greedy match:

str.match(/mailto:([^ ]*?( |$|\n))|http:\/\/([^\/]*?)( |$|\n)/) 

You can add more checking for valid email addresses, etc. if you'd like.

Once you've got the string, you can use auto_link to make a link from it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜