Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close all HTML unclosed IMG tags

Tags:

Is it possible to do a regex replace on all IMG tags that are unclosed? If so, how would I identify:

  <img src="..." alt="...">

...as a potential canidate to be replaced?

   = <img src="..." alt="..."/>

Update: We have hundreds of pages, and thousands of image tags, all must of which must be closed. I'm not stuck on RegEx -- any other method, aside from manually updating all IMG tags, would suffice.

like image 332
George Johnston Avatar asked Mar 12 '10 15:03

George Johnston


People also ask

Is there a closing tag for IMG?

The <img /> Tag To add an image to your website you will need to use the <img> tag. This tag is different than other tags, in that it has no closing tag. It is called a self-closing tag, which means that there is just a slash at the end of the opening tag (ex.

Should we close IMG tag in HTML?

<img> HTML – Image Tag Tutorial. In HTML, you use the <img> tag to add images to websites. It is an inline and empty element, which means that it doesn't start on a new line and doesn't take a closing tag (unlike the paragraph ( <p> ) tag, for instance).


2 Answers

(<img[^>]+)(?<!/)>

will match an img tag that is not properly closed. It requires that the regex flavor you're using supports lookbehind (which Ruby and JavaScript don't but most others do). Backreference no. 1 will contain the match, so if you search for this regex and replace by \1/> you should be good to go.

If you need to account for the possibility of > inside attributes, you could use

(<img("[^"]*"|[^>])+)(?<!/)>

This will match, e.g.,

<img src="image.gif" alt="hey, look--->">
<img src="image/image.gif">

and leave

<img src="image/image.gif" />

alone.

like image 50
Tim Pietzcker Avatar answered Sep 17 '22 17:09

Tim Pietzcker


In HTML the end tag for an <img> "must be omitted", so the start tag closes the element and you can't have an unclosed img.

If you want to convert your HTML to XHTML then use a real parser. Regular Expressions aren't a very good tool for this job.

like image 39
Quentin Avatar answered Sep 17 '22 17:09

Quentin