str_replace计数$ placeholder的出现次数,替换为相应的$ variable

时间:2013-03-22 02:08:16

标签: php parameters count str-replace

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

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

占位符是[image]。对于每个新帖子,我上传了多个图像,但每个帖子可能会有1-10个图像,因此放置了可变数量的[图像]占位符。我有一个功能,可以获得该帖子的所有相关图像,并计算有多少图像。

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分: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'];