麻烦在循环中连接字符串

时间:2011-03-20 19:32:39

标签: php string concatenation

我尝试按顺序对我的ZenPhoto安装进行一些更改,以便在相册页面的底部我有一个文本区域,显示上面生成的图像的“嵌入”代码,以便读者可以简单地复制它并将html发布到他们自己的网站上。

以下是代码片段。

<?php $str  = ''; ?>
<?php while (next_image()): ?>
    <div class="imagethumb"><a href="<?php echo html_encode(getImageLinkURL());?>" title="<?php echo getBareImageTitle();?>"><?php printImageThumb(getAnnotatedImageTitle()); ?></a></div>

     $str .= '<a href="<?php echo html_encode(getImageLinkURL());?>" title="<?php echo getBareImageTitle();?>"><?php printImageThumb(getAnnotatedImageTitle()); ?></a>;'
<?php endwhile; ?>

<textarea type="text" size="50">
     <?php echo $str; ?>
</textarea>

我添加的代码是$ str的东西。我正在尝试遍历图像并创建在while循环中的第一个div中使用的html,以便将其作为文本放入str字符串中。这是为库中的每个图像连接的,然后将结束str发布到一个简单的文本区域供用户复制。

我无法让$ str concatination工作。

我是php的新手,我无法完全掌握语法。

非常感谢任何帮助。

4 个答案:

答案 0 :(得分:5)

连接不在<?php标记内。为了便于阅读,您应该使用sprintf

<?php $str  = ''; ?>
<?php while (next_image()): ?>
    <div class="imagethumb"><a href="<?php echo html_encode(getImageLinkURL());?>" title="<?php echo getBareImageTitle();?>"><?php printImageThumb(getAnnotatedImageTitle()); ?></a></div>

     <?php $str .= sprintf('<a href="%s" title="%s">%s</a>', 
                           html_encode(getImageLinkURL()),
                           getBareImageTitle(),
                           printImageThumb(getAnnotatedImageTitle()));
     ?>
<?php endwhile; ?>

但是你在这里重复一些事情(你要创建两次链接)。您可以稍微重新构建代码以避免这种情况:

<?php 
   $images = array();
   while (next_image()) {
       $images[] = sprintf('<a href="%s" title="%s">%s</a>', 
                               html_encode(getImageLinkURL()),
                               getBareImageTitle(),
                               printImageThumb(getAnnotatedImageTitle()));
   }
?>
<?php foreach($images as $image): ?>
    <div class="imagethumb"><?php echo $image; ?></div>
<?php endforeach; ?>

<textarea>
     <?php echo implode("", $images); ?>
</textarea>

参考: implode

答案 1 :(得分:0)

你的php代码在你的php块之外开始和结束,中间有随机的php块。

<?php $str .= '<a href="';
$str .= html_encode(getImageLinkURL());
$str .= '" title="';
$str .= getBareImageTitle();
$str .= '">';
$str .= printImageThumb(getAnnotatedImageTitle());
$str .= '</a>';
?>

可替换地:

<?php $str .= '<a href="'.html_encode(getImageLinkURL()).'" title="'.getBareImageTitle().'">'.printImageThumb(getAnnotatedImageTitle()).'</a>'; ?>

答案 2 :(得分:0)

$str变量未包含在<?php ?>标记中。

答案 3 :(得分:0)

一个问题是'"字符串在PHP中的行为方式不同。当你有:

echo '<?php echo $otherString; ?>';

PHP将打印:

<?php echo $otherString; ?>

而不是$otherString

的内容

我会改写这一行:

<?php $str .= '<a href="<?php echo html_encode(getImageLinkURL());?>" title="<?php echo getBareImageTitle();?>"><?php printImageThumb(getAnnotatedImageTitle()); ?></a>' ?>

看起来更像这样:

<?php $str .= '<a href="' . html_encode(getImageLinkURL()) . '" title="' . getBareImageTitle() . '" ' . printImageThumb(getAnnotatedImageTitle() . '</a>;'; ?>

另一个问题是你不能echo成一个字符串并让它连接起来。相反,您想要返回一个字符串值。