0

Please see the next code.

<p>
<img src="http://jdjd" alt="" /><br />
Hola mama<br />
fdffdfdfdfd <img src="http://jdjd" alt="" /><br />
<img src="http://jdjd" alt="" /><br />
<span>Hola</span>
</p>

Then, the following draw it

enter image description here

Note that I've inserted three <img>, two of them are the only element in a line and the another one is next to a text (fdffd.. + img).

I don't know how to resolve this issue, but I would like when a <img> is not the only element in a line, insert a class called center. So the result would be the next:

<p>
<img class="center" src="http://jdjd" alt="" /><br />
Hola mama<br />
fdffdfdfdfd <img src="http://jdjd" alt="" /><br />
<img class="center" src="http://jdjd" alt="" /><br />
<span>Hola</span>
</p>

I guess this can be resolve using Regular Expressions, but I don't know how to use it.

Darf Zon
  • 6,268
  • 20
  • 90
  • 149
  • You mean you would like to insert `center` when it's the only thing in that line, don't you? – jAC Jan 21 '13 at 17:18
  • Please try to explain exactly what condition you need to insert "center" class. Also adding details on where do you want to do that would help (obviously it is not ASP.Net site as you'd not show code like that in this case). – Alexei Levenkov Jan 21 '13 at 17:22
  • So, you want to add the class to any image alone on a line (or possibly the other way around)? Just a note: [Regexes can not do that for you](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags). You'll want an HTML parser. – femtoRgon Jan 21 '13 at 17:23
  • @JanesAbouChleih yes, that exactly what I like! – Darf Zon Jan 21 '13 at 17:28
  • @AlexeiLevenkov What I've seen, this behavior happened when starts with `<[p or br or span]>[p or br or span]>` – Darf Zon Jan 21 '13 at 17:32
  • Consider using HtmlAgilityPack and finding nodes that match your condition... Regular expressions will not help you here. – Alexei Levenkov Jan 21 '13 at 18:30
  • @Alexei - I agree with using HtmlAgilityPack or some other equivalent as the preferred option. However, this _can_ be done with regex as my answer shows. – robinCTS Jan 27 '13 at 02:38

1 Answers1

0

Use the regex:

(</?(?:p|br|span)(?: */)?>\s*<img )([^>]*>\s*</?(?:p|br|span)(?: */)?>)

with the replacement string:

"$1class='center' $2"

Explanation:

(                                 (Begin Group 1)
    </?(?:p|br|span)(?: */)?>     Find an opening or closing p, br or span tag
    \s*<img[ ]                    Followed by the start of a img tag
)                                 (End Group 1)
(                                 (Begin Group 2)
    [^>]*>                        Followed by the rest of the img tag
    \s*</?(?:p|br|span)(?: */)?>  Followed by an opening or closing p, br or span tag
)                                 (End Group 2)
robinCTS
  • 5,746
  • 14
  • 30
  • 37