0

I would like to insert a break after any text before few or one img tag:

I have a text:

Some text, some text <img src="thumb.jpg" /><img src="thumb2.jpg" />

I would like to get:

Some text, some text <br /><img src="thumb.jpg" /><img src="thumb2.jpg" />

I would like to make it through the regular expression in Ruby using the gsub method.

isqad
  • 290
  • 2
  • 10
  • Based on what you are saying shouldn't it be "Some text, some text

    " ? Notice the second
    tag.
    – coolmine Mar 25 '13 at 12:51
  • Sorry, I edited the question – isqad Mar 25 '13 at 12:57
  • I think this warrants a link to the main question on these sorts of things: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags. Use a library. – Linuxios Mar 25 '13 at 13:52

2 Answers2

3

Maybe this?

str.gsub(/((?:<img[^>]+>)+)/, '<br />\1')

Depends on how you define text, you might need some alteration on the Regexp to make a correct substitution.

Arie Xiao
  • 13,909
  • 3
  • 31
  • 30
0

It sounds like you should actually use sub instead of gsub, so that it only changes the first instance of the <img> tag that you encounter:

s.sub(/<img/, '<br /><img')
Brandan
  • 14,735
  • 3
  • 56
  • 71