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
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>")
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With