0

I have a string like this:

'<img src="image1.jpg"><img src="image2.jpg"><img src="image3.jpg">
<img src="image4.jpg"><img src="image5.jpg">'

I'd like to come to:

'<div class="slide"><img src="image1.jpg"><img src="image2.jpg"></div>     
<div class="slide"><img src="image2.jpg"><img src="image3.jpg"></div>
<div class="slide"><img src="image3.jpg"></div>'

So basically I'd like to apply a preg_replace to wrap every 2 elements in a DIV.

I searched the forum and found some tips that I tried:

$pattern = '/(<img[^>]*class=\"([^>]*?)\"[^>]*>)+/i';
$replacement = '<div class="slide">$1</div>';
$content = preg_replace($pattern, $replacement, $content);

and

$pattern = '/(<img[^>]*class=\"([^>]*?)\"[^>]*>){2,}/i';
$replacement = '<div class="slide">$1</div>';
$content = preg_replace($pattern, $replacement, $content);

But it doesn't work...

Any idea, guys?

Thank you!

2 Answers2

2

Use DomDocumen object to do it:

$str = '<img src="image1.jpg"><img src="image2.jpg"><img src="image3.jpg">
<img src="image4.jpg"><img src="image5.jpg">'; 
$dom = new DomDocument;
$dom->loadHTML($str);
$imgs = $dom->getElementsByTagName('img');

$i = $imgs->length;
$cur = 0;
$res = new DomDocument;

while ($i >= 2) {
   $div = $res->createElement('div');
   $div->setAttribute("class","slide"); 
   $res->appendChild($div);
   $div->appendChild($res->importNode($imgs->item($cur++)));
   $div->appendChild($res->importNode($imgs->item($cur++)));
   $i -= 2;   
}
if($i)  $res->appendChild($res->importNode($imgs->item($cur++)));

echo $res->saveHTML();

// <div class="slide"><img src="image1.jpg"><img src="image2.jpg"></div><div class="slide"><img src="image3.jpg"><img src="image4.jpg"></div><img src="image5.jpg">
splash58
  • 26,043
  • 3
  • 22
  • 34
0

Here is working example:

<?php

$content = '<img src="image1.jpg"><img src="image2.jpg">
<img src="image3.jpg"><img src="image4.jpg">
<img src="image5.jpg">';

$pattern = '/((<img[^>]*src=\"([^>]*?)\"[^>]*>\s*){2,2})/i';
$replacement = '<div class="slide">$1</div>';
$content = preg_replace($pattern, $replacement, $content);

echo $content;

It is your second example, but with 4 fixes:

  1. class -> src
  2. added block () to catch 2 items
  3. fixed quantity {2,} -> {2,2} (change it to {1,2} if you want to catch last one img tag)
  4. \s* added to catch spaces and line breaks between img tags
oakymax
  • 1,454
  • 1
  • 14
  • 21
  • Thank you much, it works! But as it only works every 2 items, the 5th picture isn't wrapped in a div. I'd rather like it to come to: `
    ` So I'm wondering if preg_replace is a good solution...
    – user3240470 Jul 08 '16 at 08:29
  • if you'll change {2,2} to {1,2} then it should work as you expected. – oakymax Jul 08 '16 at 08:54