2

i have this html content :

<p><img src="##" />
</p>
<p>

<img src="##" />
</p>
<p>
</p>
<p class="ss"><a href="ss">
    <img src="####" />
</a></p>

i want to extract all paragraphs and all their images and reformat the html so i can have images first then the folowing paragraph this is an example :

<img src="##" /><p>
</p>
<img src="##" />
<p>


</p>
<p>
</p>
<img src="####" />
<p class="ss"><a href="ss">

</a></p>

i tried something but it won't work :

$result = preg_replace('/(<p\b[^><]*)>(.+?)(<img([^>]*)\/>)(.+?)(<\/p>)/is', '$2 $4', $text);
Andy Lester
  • 91,102
  • 13
  • 100
  • 152
Abdou Tahiri
  • 4,338
  • 5
  • 25
  • 38

2 Answers2

0

This is very crude and may match more than you want it to, but in very simple scenarios, this may work:

$result = preg_replace('/(<p[^>]*>)(.*?)(<img[^>]*>)/is', '$3$1$2', $text);

This is probably better:

$result = preg_replace('/(<p[^>]*>)([^<]*)(<img[^>]*>)/is', '$3$1$2', $text);
Robert McKee
  • 21,305
  • 1
  • 43
  • 57
  • Seems to work how I designed it. It wasn't meant to pull img tags when nested. It could, but then it would also incorrectly pull some images that it shouldn't. The assumption I made based on the OP's examples is that the img tag would immediately follow the p tag opening, and I only pull those. In your example, you pulled an img tag out of an anchor tag, which would then render the anchor useless and the img unclickable. – Robert McKee Nov 03 '15 at 18:10
  • In that case, you would probably want to pull both the anchor tag and img tag out of the p, but that isn't what he asked for -- better to be safe than to go mangling the source when situations arise that are undefined. – Robert McKee Nov 03 '15 at 18:13
0

this work for me , it looks for each paragraph that contains any content and an image, so i can match all images and their containing paragraphs.

$pattern = '/(<p\b[^><]*>)(((?!<\/p>).?)*)(<img.*?\/\>)(((?!<\/p>).?)*)(<\/p>)/s';
Abdou Tahiri
  • 4,338
  • 5
  • 25
  • 38