-2

How can I get preg_replace to perform multiple replacements on the same string with different values at different places?

I actually have a comma separated string of image paths, that I split into multiple <img src="">tags like below.

$a = /images/us/US01021422717777-%s.jpg,/images/us/US01021422717780-%s.jpg

Then I do:

preg_replace('~\s?([^\s,]+)\s?(?:,|$)~','<img class="gallery" src="$1" data-slide="$1"></div>', $a)

Which gives me:

<img src="/images/us/US01021422717777-%s.jpg" data-slide="/images/us/US01021422717777-%s.jpg"> <img src="/images/us/US01021422717780-%s.jpg" data-slide="/images/us/US01021422717780-%s.jpg">

What can I do to replace the first %s with m and the second %s with %l, using additional code in the same preg_replace statement itself. Without using preg_callback etc.

So my end results look like:

<img src="/images/us/US01021422717777-m.jpg" data-slide="/images/us/US01021422717777-l.jpg"> <img src="/images/us/US01021422717780-m.jpg" data-slide="/images/us/US01021422717780-l.jpg">

I tried using sprintf, but it appears that will not work in this situation.

sprintf(preg_replace('~\s?([^\s,]+)\s?(?:,|$)~','<img class="gallery" src="$1" data-slide="$1"></div>', $a),'m','l')

I'm sure you get the idea of what I'm trying to do. Any help on this?

Norman
  • 6,159
  • 23
  • 88
  • 141
  • 1
    You asked [the same question](http://stackoverflow.com/questions/28254349/php-using-str-replace-along-with-preg-replace) yesterday. I provided you [an answer](http://stackoverflow.com/questions/28254349/php-using-str-replace-along-with-preg-replace/28254473#28254473) for it. Isn't it working? – axiac Feb 01 '15 at 12:11

1 Answers1

1

Well you could try not to capture the %s part. Supposing it's always before the extension, you could do :

preg_replace('~\s?([^\s,]+)-%s(\.[a-z]+)\s?(?:,|$)~i','<img class="gallery" src="$1-m$2" data-slide="$1-l$2"></div>', $a)
Cimbali
  • 11,012
  • 1
  • 39
  • 68