Str_replace计算$占位符出现的次数,用相应的$变量替换



我已经尝试了好几天了。我在每个帖子中都有一个描述,其中有占位符手动放置在我想要替换相应图像的地方。例如:

This is the description shortened...
[image]
[image]
Description starts again with a new paragraph continuing...

占位符是[image]。每篇新文章我都会上传多张图片,但每篇文章的图片数量可能从1-10张不等,因此放置了可变数量的[image]占位符。我有一个函数,它获取与该帖子相关的所有图像,并计算有多少图像。

这是我到目前为止的代码,但问题是,对于前两个占位符[image],它显示第一个相关图像两次,然后循环并再次显示描述,这次用第二个图像替换两个[image]占位符。

<?php
  foreach ($photos as $picture) {
    $count = count($picture);
    for($i = 1; $i<= $count; $i++) {
      $image = $picture['filename'];
      $replace = "[image]";
      $image_path = '../../content_management/image_upload/';
      $placeholders = array("$replace");
      $image_location = array('<a class="fancybox" href="' . $image_path . '' . $image . '" data-fancybox-group="gallery"><img src="' . $image_path . '' . $image . '" /></a>');
      $rawstring = $photo_article['description'];
      $new_string = $rawstring;
      $new_string = str_replace($placeholders, $image_location, $new_string, $i);
      echo $new_string;
    }
  }
?>

输出是:

This is the description shortened...
Image1.jpg
Image1.jpg
Description starts again with a new paragraph continuing...
This is the description shortened...
Image2.jpg
Image2.jpg
Description starts again with a new paragraph continuing...
$photos = array(
    'photo1' => array(
    'filename' => 'image1.png'
    ),
    'photo2' => array(
    'filename' => 'image2.png'
    ),
);
$photo_article['description'] = "This is the description shortened...
[image]
[image]";
foreach ($photos as $picture)
{
    $image = $picture['filename'];
    $image_path = '../../content_management/image_upload/';
    $replacement = '<a class="fancybox" href="' . $image_path . '' . $image . '" data-fancybox-group="gallery"><img src="' . $image_path . '' . $image . '" /></a>';
    $photo_article['description'] = preg_replace("~[image]~s", $replacement, $photo_article['description'], 1);
}
    echo $photo_article['description'];

你在循环调用同一个$picture['filename']它应该是$picture[$i]['filename']或者只是foreach ($picture as $thisPic) { $thisPic['filename']; }

最新更新