Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically link URLs and images within html string

Hi i have a string like this:

"<p class='video'>http://vimeo/2342343</p><p class='image'>http://nerto.it/logo.png</p><p class='text'>try to write</p><p class='video'>http://vimeo/2234923</p>"

i have to transform it in a string like this:

"<p class='video'><a href='http://vimeo/2342343'>http://vimeo/2342343</a></p><p class='image'><img src='http://nerto.it/logo.png' /></p><p class='text'>try to write</p><p class='video'><a href='http://vimeo/2234923'>http://vimeo/2234923</a></p>"

so how i can get every element and transform it?

thanks

like image 854
Luca Romagnoli Avatar asked Jan 26 '11 22:01

Luca Romagnoli


2 Answers

You can use the auto-link function to convert links into actual anchor tags.

auto_link(text_to_convert)

*Notice: Method deprecated or moved This method is deprecated or moved on the latest stable version. The last existing version (v3.0.9) is shown in the link.

If you have more specific use cases you'll probably want to use gsub with a regular expression. For example:

text.gsub(/\<p\s+class=\'image\'\>(.*?)\<\/p\>/, "<p class='image'><img src='\\1' /></p>")
like image 54
Pan Thomakos Avatar answered Oct 12 '22 22:10

Pan Thomakos


html = "<p class='video'>http://vimeo/2342343</p>
        <p class='image'>http://nerto.it/logo.png</p>
        <p class='text'>try to write</p>
        <p class='video'>http://vimeo/2234923</p>"

linked = html.gsub( %r{http://[^\s<]+} ) do |url|
  if url[/(?:png|jpe?g|gif|svg)$/]
    "<img src='#{url}' />"
  else
    "<a href='#{url}'>#{url}</a>"
  end
end

puts linked
#=> <p class='video'><a href='http://vimeo/2342343'>http://vimeo/2342343</a></p>
#=> <p class='image'><img src='http://nerto.it/logo.png' /></p>
#=> <p class='text'>try to write</p>
#=> <p class='video'><a href='http://vimeo/2234923'>http://vimeo/2234923</a></p>
like image 33
Phrogz Avatar answered Oct 13 '22 00:10

Phrogz