且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-12-08 21:00:31

如果你不回显或连接< img> 并将文件名添加到数组中,你可以轻松生成你想要的标记。

If you don't echo or concatenate the <img> and add the filename to an array you can easily generate the markup you want.

<?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";
    }
?>