我能够解析目录并使用以下任何功能列出所有图像。我只需要在循环中最后一个元素的img标记中插入一个class =“last”属性。
此外,哪些功能最适合我正在尝试做的事情?
非常感谢任何帮助!
function get_images1() {
$exts = 'jpg jpeg png gif';
$str = ''; $i = -1; // Initialize some variables
$folder = './wp-content/uploads';
$handle = opendir($folder);
$exts = explode(' ', $exts);
while (false !== ($file = readdir($handle))) {
foreach($exts as $ext) { // for each extension check the extension
if (preg_match('/\.'.$ext.'$/i', $file, $test)) { // faster than ereg, case insensitive
//$str .= $file;
$str .="<img src='wp-content/uploads/". $file ."' alt='" . $file . "' />";
//if ($str) $str .= '|';
++$i;
}
}
}
echo $str;
closedir($handle); // Were not using it anymore
return $str;
}
function get_images2() {
//Open images directory
$dir = @ opendir("wp-content/uploads/");
//List files in uploads directory
while (($file = readdir($dir)) !== false)
{
if(ereg("(.*)\.(jpg|bmp|jpeg|png|gif)", $file))
{
echo '<img src="wp-content/uploads/'. $file .'" alt="" />';
}
}
closedir($dir);
}
function get_images3() {
$dir = 'wp-content/uploads/';
$files = scandir($dir);
//print_r($files);
$num = count($files);
for($n=0; $n<$num; $n++)
{
if(ereg("(.*)\.(jpg|bmp|jpeg|png|gif)", $files[$n]))
{
echo '<img src="wp-content/uploads/'. $files[$n] .'" alt="" />';
}
}
}
function get_images()
{
$directory = 'wp-content/uploads/';
$directory_stream = @ opendir($directory);
// Display information about the directory stream
// print_r ($directory_stream);
while ($entry = readdir ($directory_stream))
{
if (! is_file ("$directory/$entry"))
continue;
echo '<img src="wp-content/uploads/'. $entry .'" alt="" />';
}
}
答案 0 :(得分:3)
如果您不回显或连接<img>
并将文件名添加到数组中,则可以轻松生成所需的标记。
<?php
$dir = 'wp-content/uploads/';
$imgs = array();
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (!is_dir($file) && preg_match("/\.(bmp|jpe?g|gif|png)$/", $file)) {
array_push($imgs, $file);
}
}
closedir($dh);
} else {
die('cannot open ' . $dir);
}
foreach ($imgs as $idx=>$img) {
$class = ($idx == count($imgs) - 1 ? ' class="last"' : '');
echo '<img src="' . $dir . $img . '" alt="' .
$img . '"' . $class . ' />' . "\n";
}
?>
答案 1 :(得分:3)
我会使用DirectoryIterator获取所有文件,使用自定义FilterIterator进行过滤,然后使用CachingIterator检查最后一个元素:
class ExtensionFilter extends FilterIterator {
public function accept() {
return $this->current()->isFile() && preg_match("/\.(bmp|jpe?g|gif|png)$/", $this->current()->getBasename());
}
}
$it = new CachingIterator(new ExtensionFilter(new DirectoryIterator($dir)));
foreach ($it as $dir) {
$filename = $dir->getFilename();
echo '<img src="'.$filename.'" '.($it->hasMore() ? '' : ' class="last"').'>';
}