PHP 脚本解析目录,列出所有图像并将类 ="last"添加到目录中的最后一个图像

标签 php image loops

我能够解析目录并列出具有以下任何功能的所有图像。我只需要在循环中最后一个元素的 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="" />';
    }
}

最佳答案

如果您不回显或连接 <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";
    }
?>

关于PHP 脚本解析目录,列出所有图像并将类 ="last"添加到目录中的最后一个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1711715/

相关文章:

php - 如何加密数据以便用LIKE执行SQL查询?

php - 将 php 数组填充到 HTML 表中

java - 如何将 String 转换为从 sqlite 获取的 Uri 并将其设置在 ImageView 中?

php - 如何使用 PHP 上传音频(mp3、ogg、flac)?

循环运行 H2O 的 Auto ML

PHP 日期时间 DST

php - 获取 1-200 之间的随机数,但忽略从查询中读取的数字

javascript - 在 Safari 上获取响应式图片的 currentSrc

C 预处理器 for 循环

c# - 如何查看用户是否未在 C# 中输入有效条目