使每行数组成为一个单独的字符串php

时间:2015-04-03 23:42:16

标签: php arrays string implode

我正在努力使图片文件在扫描目录时显示为图片而不是链接。以下是我用来查找文件的内容:

$images=glob(getcwd().'/*{jpeg,gif,png}', GLOB_BRACE);
$pattern=implode("<br>", $images)."<br>";

这给了我这个:

/students/levans10/public_html/cs130a/images.gif
/students/levans10/public_html/cs130a/jpg-44.png

如何将这些行中的每一行称为字符串?

这是我的整个代码对我不起作用:

<?php

function showImage() {
$filelist = glob(getcwd()."/*");
$path= getcwd();
$array = explode("/", $path);
$filename=implode("/", array_slice($array, 4));
$user=implode("/", array_slice($array, 2, 1));
$images=glob(getcwd().'/*{jpeg,gif,png}', GLOB_BRACE);
$pattern=implode("<br>", $images)."<br>";

echo implode("<br>", $images);

if ($filelist != false) {
print "<p>Here are the folders and files in".getcwd().":</p>";
foreach ($filelist as $file) {
  if(ereg($pattern, $file)) {
  $url = "http://hills.ccsf.edu/~".$user."/".$filename."/" . substr($file, strrpos($file, '/') + 1);
  print "<a href=".$url."><img src=".$url." height='100' width='100'></a><br><br>";
       }
  if(!ereg($pattern, $file)) {
  $url = "http://hills.ccsf.edu/~".$user."/".$filename."/" . substr($file, strrpos($file, '/') + 1);
  print "<a href=".$url.">".$url."</a><br><br>";        
    }
}
} else {
print "<a href=".$url.">".$url."</a><br><br>";
}
}

showImage();

?>

我尝试过使用:     (!feofif(ereg($pattern, $file))))

但这并不是正确使用!feof所以它会显示照片但会发出大量其他警告。

1 个答案:

答案 0 :(得分:0)

您希望显示指向所有文件的链接,但是对于要显示图像的图像也是如此。您希望仍然链接到所有文件的事实似乎是您的问题 description 中缺少的信息块。

如前所述,在评论中,快速修复&#34;只是用if(ereg($pattern, $file)) {更改if (in_array($file,$images)) {。并将第二部分包含在一个else块中,如果否定表达式,请不要使用另一部分!换句话说......

if (in_array($file,$images)) {
    /* Link and display image */
} else {
    /* Just link the file */
}

或者,您可以在逐步浏览$filelist时检查每个文件是否为图像,而不是在循环之前执行此操作(并将这些文件存储在另一个名为{{1}的数组中然后你需要查找)。并通过在$images块之外移动$url作业来避免重复代码。例如:

if

(不要使用$url = '<Construct URL before IF block>'; if (preg_match('/\.(jpe?g|gif|png)$/i',$file)) { /* Link and display image */ } else { /* Just link the file */ } 来匹配正则表达式 - 在PHP 5.3中不推荐使用此函数。请改用ereg()。)

如果必须以这种方式构造HTML,那么在完成后(在循环结束时)将其构建在字符串变量和preg_replace()中一次。不要回声,回声,回声等。例如:

echo