开发者

Autodetect a value type in a string in order to consider that an URL, e-mail address,

开发者 https://www.devze.com 2023-03-09 07:10 出处:网络
I am using Ruby on Rails 3 and I would like to show URLs and e-mail addresses as links in a view. I retrieve the URL and the e-mail address information as typed by a user in a form input text field, s

I am using Ruby on Rails 3 and I would like to show URLs and e-mail addresses as links in a view. I retrieve the URL and the e-mail address information as typed by a user in a form input text field, so I will need to use a regular expression...

How can I do?


BTW:

From here I have the following regexp:

(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))

When I try to state the above regexp in my class I have a trouble because there is an error in the reg_url declariation:

class User < ActiveRecord::Base

  def check
    reg_url = (?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))
    ...
  end

end

Maybe, to solve this problem I have to insert at the end of bottom some other chars (example开发者_StackOverflow中文版 '\', '/', ...)...


If I understand correctly, then in a string you wish to turn all the links and email addresses into anchor tags?

If so, then you should try the auto_link method.

Usage:

auto_link("Go to http://www.rubyonrails.org and say hello to david@loudthinking.com")
# => "Go to <a href=\"http://www.rubyonrails.org\">http://www.rubyonrails.org</a> and
#     say hello to <a href=\"mailto:david@loudthinking.com\">david@loudthinking.com</a>"

You may need to include the keyword "raw" before the auto_link call if the html appears escaped upon output.

0

精彩评论

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