简体   繁体   中英

How to display images found in a directory and using name info in their filename

Lets say I have 4 jpg files in a directory that will only ever contain jpg files. The number of files may change, the naming convention will always be Name-file.jpg

Bob-file.jpg
Tom-file.jpg
Dave-file.jpg
Douglas-file.jpg

I am trying to come up with a php script that will look at the directory and display each image (as in viewing the picture, not just listing the filename) in the web browser and also add the persons name along side it so I can see who it is.

I have tried playing with arrays and loops but can't get anything remotely close (I'm new to PHP) Thanks!!

You'll want something roughly along these lines. Using a directory iterator to get all the filenames and then using a regular expression to extract the name from the filename.

foreach ((new DirectoryIterator('./path/to/image/dir')) as $file) {
    if (!$file->isDot() && preg_match('#^(.+)\-file\.jpg$#uD', $file->getFilename(), $details) === 1) {
        printf('<div><img src="%s" alt="Picture of %s">%s</div>',
            htmlentities( '/web/path/to/images/' . $details[0] ),
            htmlentities( $details[1] ),
            htmlentities( $details[1] )
        );
    }
}
<?php
$directory_to_read_from = './imgage_directory';
if ($handle = opendir($directory_to_read_from))
{
    while (false !== ($entry = readdir($handle)))
    {
        if ($entry != "." && $entry != "..")
        {
            $name = explode('-', $entry);
            echo '<h1>' . $name[0] . "</h1><img src='$directory_to_read_from/$entry' /><br>";
        }
    }
    closedir($handle);
}

在此处输入图像描述

OUTPUT:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM