I need to find out the content before <img>
tag in my HTML if it does not have <br/>
before it. And if <img>
jas some other content before it then I need to add <br/>
before it.
Asked
Active
Viewed 115 times
-1

Shiv Kumar Ganesh
- 3,799
- 10
- 46
- 85

castors33
- 477
- 10
- 26
-
1don't use regex in this case. use a dom parser. god knows there are plenty – gion_13 Jul 03 '12 at 20:15
-
3[Do not parse HTML with regex](http://stackoverflow.com/a/1732454/451590). Use a full HTML parser instead. – David B Jul 03 '12 at 20:15
-
Also, what language are you using? (Does it have negative backreferences in its RE language variant?) – Donal Fellows Jul 03 '12 at 20:16
-
1Here is all you EVER need to know about HTML and regex: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – Kasapo Jul 03 '12 at 20:16
-
Have you tried using an XML parser instead? – Kasapo Jul 03 '12 at 20:17
-
Xpath route, if taken, would probably be along the lines of `//img[not(preceding-sibling::br)]` – Wrikken Jul 03 '12 at 20:17
-
Any dom parser would do the trick use JQuery!! – Shiv Kumar Ganesh Jul 03 '12 at 20:31
-
well I would have prefer to not need to use things like that because I only use a few HTML in my software...but I guess I don't have long range of choices – castors33 Jul 03 '12 at 20:34
-
1@castors33 A small script would solve your problem. I have mentioned below. Just have a look.You just need to include the JQuery file.Hope things work correctly. – Shiv Kumar Ganesh Jul 03 '12 at 20:41
2 Answers
1
Consider this html code :- (This solution uses JQuery!)
<h1><img src="#"/><h1>
<br/><img src="#"/>
Now in one case you need to get the element before <img>
$(document).ready(
function(){
$('img').each(function(){
if($(this).prev()==$('br'))
{
$(this).prev().replaceWith('');
}
if($(this).prev()!=$('br)')
{
$(this).prev().replaceWith('br');
}
});
});
Guess this would solve your problem.

Shiv Kumar Ganesh
- 3,799
- 10
- 46
- 85
1
A slightly simpler and faster version
$(document).ready(function(){
$('img').each(function(){
var prev = $(this).prev();
if (prev[0] && prev[0].nodeName.toUpperCase() !== 'BR') {
prev.after('<br>')
}
})
})

SMathew
- 3,993
- 1
- 18
- 10