Joseph Webber
Joseph Webber

Reputation: 2173

How can I check if a file exists with a certain string in its filename?

I'd like to be able to search a directory for a file that starts with a specific string, for example:

- foo
  - 1_foo.jpg
  - 2_bar.png

How would I check directory foo for files that begin with "1_"?

I've tried using file_exists and preg_match like so:
if (file_exists("foo/" . preg_match("/^1_/", "foo/*"))) echo "File exists.";
but this doesn't work.

Upvotes: 2

Views: 5209

Answers (4)

ArtFranco
ArtFranco

Reputation: 360

I was having some trouble checking a directory and files and I gather some scripts here and there and this worked for me (Hope it helps u too):

if ($handle = opendir('path/to/folder/')) 
{
    while ( false !== ($entry = readdir($handle)) ) {
        if ( $entry != "." && $entry != ".." ) {
        // echo "$entry<br>";
            if (preg_match("/^filename[0-9]_[0-9].jpg/", $entry))
            {
                // $found_it = TRUE;
            }
        }
    }

    closedir($handle);
}

Upvotes: 0

Edgar Orozco
Edgar Orozco

Reputation: 2782

You can use the glob() function

<?php
$list = glob('1_*.*');
var_dump($list);

Upvotes: 0

three3
three3

Reputation: 2846

Sounds like you need the glob() function. The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells.

<?php
foreach (glob('1_*.*') as $filename) {
    echo "$filename\n";
}
?>

The above example will output something similar to:

1_foo.png
1_bar.png
1_something.png

Upvotes: 6

Brian White
Brian White

Reputation: 8716

Sorry, but the filesystem doesn't understand wildcards or regular expressions. To accomplish what you want, you have to open the directory and read its contents, getting a list of all the files in that directory. Then you use standard string utilities to see which filenames match your criteria.

I think PHP's scandir is what you want as a starting point. You can also use glob but that actually forks a shell to get the file list (which in turn will do the C equivalent of scandir()).

Upvotes: 1

Related Questions