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


make each line of array an individual string php

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

$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所以它显示了图片,但随后发布了大量其他警告。

您希望显示指向所有文件的链接,但对于图像,您也希望显示图像。事实上,你仍然想链接到你的所有文件,这似乎是你的问题描述中缺失的信息。

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

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

或者,您可以在遍历$filelist时检查每个文件是否为图像,而不是在循环之前检查(并将这些文件存储在另一个名为$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 */
}

(不要使用ereg()来匹配正则表达式-此函数在PHP 5.3中已被弃用。请改用preg_replace()。)

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

$html = '';
foreach ($filelist as $file) {
    /* ... */
    $html .= '<Some HTML>';
    /* ... */
    $html .= '<Some more HTML>';
}
echo $html;