Luca Romagnoli Luca Romagnoli - 5 months ago 8
Ruby Question

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

Answer
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>
Comments