在 foreach 语句中更改 url
Change url in foreach statement
我们有一些代码可以从外部来源取回图像 url。我们修改
<?php
$imagez = get_field('prop_gallery_images');
foreach($imagez as $image) {
if($image['type']==0) {
?>
<img src="<?=$image?>">
<?php
}
}
?>
结果:
<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">
我想将显示 _sm 的 url 更改为 _web,因为这会带来更高分辨率的图像版本。我想过使用 preg_replace 但不确定这在 foreach 语句中如何工作,因为我以前没有这样做过?也不确定这是否是最干净的方法。
提前致谢!!
使用 str_replace 一样简单:
<img src="<?= str_replace('_sm', '_web', $image);?>">
如果您想要一个 "clean" 数组开始(例如抽象逻辑),那么您可以使用 array_map。此函数将用户定义的函数应用于数组中的每个元素。
<?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);
输出:
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
)
我们有一些代码可以从外部来源取回图像 url。我们修改
<?php
$imagez = get_field('prop_gallery_images');
foreach($imagez as $image) {
if($image['type']==0) {
?>
<img src="<?=$image?>">
<?php
}
}
?>
结果:
<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">
我想将显示 _sm 的 url 更改为 _web,因为这会带来更高分辨率的图像版本。我想过使用 preg_replace 但不确定这在 foreach 语句中如何工作,因为我以前没有这样做过?也不确定这是否是最干净的方法。
提前致谢!!
使用 str_replace 一样简单:
<img src="<?= str_replace('_sm', '_web', $image);?>">
如果您想要一个 "clean" 数组开始(例如抽象逻辑),那么您可以使用 array_map。此函数将用户定义的函数应用于数组中的每个元素。
<?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);
输出:
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
)