English 中文(简体)
PHP script to parse directory, list all images and add class="last" to the last image in the directory
原标题:

I m able to parse through the directory and list all images with any of the functions below. I just need to insert a class="last" attribute into the img tag of the last element in the loop.

Also, which of these functions works best for what I m trying to do?

Any help much appreciated!

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="" /> ;
    }
}
最佳回答

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 .   />  . "
";
    }
?>
问题回答

I would use DirectoryIterator to get all files, the filter this using a custom FilterIterator and then a CachingIterator to check for the last element:

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" ). > ;
}




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签