查找具有特定名称但可变文件扩展名的文件

I'd like to be able to select a file by just giving it's name (without extension). For example, I might have a variable $id holding 12. I want to be able to select a file called the-id-in-the-variable, say, 12.png from a directory, but it may have any one of a number of file extensions, listed below:

  • .swf
  • .png
  • .gif
  • .jpg

There is only one occurrence of each ID. I could use a loop and file_exists(), but is there a better way?

Thanks,

James

$matches = glob("12.*");

would return an array with all the matching filenames in the current directory. glob() works much the same as wildcard matching at the shell prompt.

Take a look at glob. Unfortunately, the exact semantics of the $pattern parameter is not described in the manual. But it seems your problem can be solved using this function.

Quick question to OP here:

What is the file extension of this file: somefile.tar.gz? Is it .gz or .tar.gz? :) I ask because most would answer this question as .tar.gz...