Re: newbie Q: How to say, "if the fileNAME is equal to...", or better yet, "if the fileNAME ends with '.jpg'"?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



2008/8/24 Govinda <govinda@xxxxxxxxxxxxx>:

> $ThisDir = getcwd()."/thumbs";
> $DirHandle = opendir($ThisDir);
> if ($DirHandle = opendir($ThisDir)) {
>   echo "Directory handle: $DirHandle\n";
>   echo "Files:<br /><hr width=\"25\%\" align=\"left\" />";
>
> while ((false !== ($file = readdir($DirHandle))) & 1) {
>        if (true == ($file="xxxx.jpg")) {
>                echo "$file<br />";
>                }
>    }
>    closedir($DirHandle);
> }
>
> But instead of printing only the name of the file which is equal to
> "xxxx.jpg", it seems to actually set the value of $file to "xxxx.jpg" on
> each iteration of the while loop, so what I get is a list of files all
> having the same name ("xxxx.jpg") and their number is equal to the actual
> number of files in that dir (plus 2 - for the "." and ".." files).
>
> How to say, "if the fileNAME is equal to...", or better yet, "if the
> fileNAME ends with '.jpg'"?

Hi, you've had a lot of responses to issues in your code snippet. I'm
just here to point out - for the sake of the archives, really - that
there are at least two more approaches you could take. PHP is one of
those languages where there's more than one way to do most things.

<?php
$path = './thumbs/' . sql_regcase ( '*.jpg' );

foreach ( glob( $path ) as $filename )
{
    echo "{$filename}<br/>";
}

You can check the manual for full details, but briefly, sql_regcase()
returns a case-insensitive regular expression, and glob() returns an
array of filenames that match the path given to it (in this case
"./thumbs/*.jpg").

<?php
$dir = new DirectoryIterator( './thumbs/' );

foreach( $dir as $file )
{
    if ( preg_match( "/jpg$/i", $file->getFilename() ) )
    {
        echo $file->getFilename() . "<br/>";
    }
}

In this one, we're iterating over a DirectoryIterator object
(http://uk2.php.net/manual/en/class.directoryiterator.php) instead of
the output of glob(). RecursiveDirectoryIterator also exists, which
allows you to traverse an entire tree, rather than just one directory.

You've already been pointed to preg_match(), so I won't explain that one again.

-- 

http://www.otton.org/category/programming/php-tips-tricks/

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux