scanE
scanE

Reputation: 342

How do I insert br tags in a string using a regular expression?

I have a string:

str = "abc xyz<img src="abc"/> 123 <img src="abc"/><img src="xyz"/>"

I want put a <br/> before the consecutive image tags at the end of the string so the resulting string will be:

str = "abc xyz<img src="abc"/> 123 <br/><img src="abc"/><img src="xyz"/>"

Only the consecutive image tags at the end of the string will be preceded by a br. How would I do this using a regular expression and the gsub method?

Upvotes: 0

Views: 546

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118271

require 'nokogiri'
require 'pp'

doc = Nokogiri::HTML::Document.parse(<<-eohtml)
"abc xyz<img src="abc"/> 123 <img src="abc"/><img src="xyz"/>"
eohtml

doc.css("img").each{|i| i.previous = '<br/>'}
puts doc.to_html

Output:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><p>"abc xyz<br><img src="abc"> 123 <br><img src="abc"><br><img src="xyz">"
</p></body></html>

As per the latest edit of OP:

require 'nokogiri'
require 'pp'

doc = Nokogiri::HTML::Document.parse(<<-eohtml)
"abc xyz<img src="abc"/> 123 <img src="abc"/><img src="xyz"/>"
eohtml
doc.css("img[src = abc]")[1].previous = "<br/>"
puts doc.to_html

Output:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><p>"abc xyz<img src="abc"> 123 <br><img src="abc"><img src="xyz">"
</p></body></html>

Upvotes: 0

Kyle d&#39;Oliveira
Kyle d&#39;Oliveira

Reputation: 6382

You could do something like

1.9.3p194 :001 > str = "abc xyz 123 <img src='smiley.gif' height='42' width='42'>"
 => "abc xyz 123 <img src='smiley.gif' height='42' width='42'>" 
1.9.3p194 :002 > str.gsub(/<img/, "<br/><img")
 => "abc xyz 123 <br/><img src='smiley.gif' height='42' width='42'>" 

Though a better solution might be to add a class to the image tags that uses CSS to push it to the next line. Possible you just need a "display:block" style

Upvotes: 1

Related Questions