1

几天来,我一直在努力实现这一目标。我在每个帖子中都有一个描述,其中手动放置了我想要替换相应图像的占位符。例如:

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

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

这是我到目前为止的代码,但问题是,对于前两个占位符 [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...
4

2 回答 2

0

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

于 2013-03-22T02:25:46.777 回答
0
$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'];
于 2013-03-22T02:34:57.547 回答