We have some code that brings back image urls from an external source. We to modify the
<?php
$imagez = get_field('prop_gallery_images');
foreach($imagez as $image) {
if($image['type']==0) {
?>
<img src="<?=$image?>">
<?php
}
}
?>
Result:
<img src="http://www.externalsource.com/store/property/165+156_sm.jpg">
<img src="http://www.externalsource.com/store/property/165+158_sm.jpg">
<img src="http://www.externalsource.com/store/property/165+159_sm.jpg">
I want to change the url where it says _sm to _web as that bring in a higher resolution version of the image. I thought of using preg_replace but not sure how this would work in a foreach statement as I have not done that before? Also not sure if this is the cleanest way of doing it.
Thanks in advance!!
As simple by using str_replace:
<img src="<?= str_replace('_sm', '_web', $image);?>">
If you want a "clean" array to start with (e.g. to abstract the logic) then you can use array_map. This function applies a user defined function to each element in an array.
<?php
$images = array(
'http://www.externalsource.com/store/property/165+156_sm.jpg',
'http://www.externalsource.com/store/property/165+158_sm.jpg',
'http://www.externalsource.com/store/property/165+159_sm.jpg',
);
$highresImages = array_map(function($url) {
return str_replace('_sm.', '_web.', $url);
}, $images);
print_r($highresImages);
Output:
Array
(
[0] => http://www.externalsource.com/store/property/165+156_web.jpg
[1] => http://www.externalsource.com/store/property/165+158_web.jpg
[2] => http://www.externalsource.com/store/property/165+159_web.jpg
)