Is there a way to write the PHP file_exists function so that it searches a directory for a file with an arbitrary extension. For instance, suppose I knew that a file were called "hello", but I didn't know the extension, how would I write a function that searched for a file called hello.* and returned the name of this file? As far as I can tell, file_exists will only search for a string.
Thanks.
You're looking for the glob()
function.
file_exists
doesn't do any kind of search : it only allows one to know whether a file exists or not, when knowing its name.
And, with PHP >= 5.3, you could use the new GlobIterator
.
$list = glob('temp*.php');
var_dump($list);
Gives me this output :
array
0 => string 'temp-2.php' (length=10)
1 => string 'temp.php' (length=8)
$list = glob('te*-*');
var_dump($list);
Yes, with two *
;-)
Will give me :
array
0 => string 'temp-2.php' (length=10)
1 => string 'test-1.php' (length=10)
2 => string 'test-curl.php' (length=13)
3 => string 'test-phing-1' (length=12)
4 => string 'test-phpdoc' (length=11)
As of PHP5.3, you can also use the GlobIterator
to search a directory with wildcards:
$it = iterator_to_array(
new GlobIterator('/some/path/*.pdf', GlobIterator::CURRENT_AS_PATHNAME) );
would return the full paths to all .pdf files in some/path in an array. The above performs about the same as glob()
, but iterators provide a more powerful and extensible API.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With