Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all a tags from string

I have a string that is being input by the user. They can add as many links as they link but we only want some users to be able to click a link. What I am trying to do is replace any a tag with just the text inside it. I have managed to do it if there is one link but can't figure out how to do it when there are multiple.

This is what I currently have and have tried many variations to get to this:

url_text = text.split("<a").last.split("</a>").first.split('>').last
text.gsub! /<a.+a>/m, url_text

But it only works for the first instance of a tag.

The string I am receiving looks like this:

text = <div>blah blah blah.<br /><br /></div>\r\n<div><a href=\"http://www.google.com\">Google</a><br />Another link: <br /> <a href=\"http://www.test.com\">Test Link</a><br /><br /></div>"

I want it to say: blah blah blah. Google Another Link: Test Link

Any help will be appreciated. Let me know if you need more code or info.

like image 334
Georgeheap Avatar asked Dec 23 '22 01:12

Georgeheap


1 Answers

You can use strip_tags (to strip all tags) or strip_links (to strip just links).

In Rails console:

> text = '<div>blah blah blah.<br /><br /></div>\r\n<div><a href=\"http://www.google.com\">Google</a><br />Another link: <br /> <a href=\"http://www.test.com\">Test Link</a><br /><br /></div>'
=> "<div>blah blah blah.<br /><br /></div>\\r\\n<div><a href=\\\"http://www.google.com\\\">Google</a><br />Another link: <br /> <a href=\\\"http://www.test.com\\\">Test Link</a><br /><br /></div>"
> helper.strip_tags(text)
=> "blah blah blah.\\r\\nGoogleAnother link:  Test Link"
like image 191
mrzasa Avatar answered Jan 05 '23 20:01

mrzasa