【问题标题】:make each line of array an individual string php使每一行数组成为一个单独的字符串 php
【发布时间】:2015-04-03 23:42:16
【问题描述】:

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

$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 的正确使用,因此它会显示图片但随后会发出大量其他警告。

【问题讨论】:

  • 如果你绝对需要单独的字符串变量而不是字符串数组,那么extract()
  • 慧,你的目标是什么?你的输出和预期输出是什么?
  • 目标是扫描目录中的文件,并将所有图像文件显示为作为链接的小图像,将所有非图像文件显示为 url。此链接显示了我的代码 link 的输出我希望这两个图像文件显示为图片。
  • @MarkBaker 我正在研究 extract(),谢谢!
  • 但是你为什么不能简单地遍历返回的数组,看起来你让这个比它需要的复杂得多

标签: php arrays string implode


【解决方案1】:

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

如前所述,在 cmets 中,“快速修复”就是将 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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 2014-08-22
    • 1970-01-01
    相关资源
    最近更新 更多