I have a string of comma separated values that comes from a database, which actually are image paths. Like so:
/images/us/US01021422717777-m.jpg,/images/us/US01021422717780-m.jpg,/images/us/US01021422717782-m.jpg,/images/us/US01021422718486-m.jpg
I then do like below, to split them at the ,
and convert them into paths for the web page.
preg_replace('~\s?([^\s,]+)\s?(?:,|$)~','<img class="gallery" src="$1">', $a)
Works well, but in one place further in my page, I need to change the -m
to -l
(which means large)
When I do like below (put a str_replace inside the preg_replace), nothing happens. How can I do something like this?
preg_replace('~\s?([^\s,]+)\s?(?:,|$)~','<img class="gallery" src="$1" data-slide="'.str_replace('-m','-l','$1').'">', $a)
Use
str_replace
onpreg_replace
returnOutput will be
You're putting the
str_replace()
call in the output pattern for thepreg_replace()
call. That meanspreg_replace()
is treating it as literal text.What you want is something like this:
But, in my opinion it would be safer and easier to debug this stuff if you changed the order of your replacement operations, something like this:
That way you don't have to whistle into your modem :-) to program that regexp.
Use
preg_replace_callback()
:Instead of the replace expression,
preg_replace_callback()
gets as its second argument a function that receives the list of matched expressions and returns the replacement string.If you need two separate outputs from each comma-separated value, I would write a pattern that stores the fullstring match and the substrings on either side of the
m
in each file.*note: I match the trailing
-
in the first capture group and the leading.
in the second capture group for minimal assurance of accuracy. This is somewhat weak validation; you can firm it up if your project requires it by adding literal or more restrictive pattern components in the capture groups.Code: (Demo)
Output:
Actually your
str_replace
is simply invoked beforepreg_replace
is invoked. Result ofstr_replace
is then passed as argument topreg_replace
.What I could suggest is using
preg_replace_callback
: