PHP file_exists 和通配符
有没有办法编写 PHP file_exists 函数,以便它在目录中搜索具有任意扩展名的文件。例如,假设我知道一个文件名为“hello”,但不知道扩展名,我该如何编写一个函数来搜索名为 hello.* 的文件并返回该文件的名称?据我所知, file_exists 只会搜索字符串。
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您正在寻找
glob()
函数。file_exists
不进行任何类型的搜索:它只允许人们在知道文件名的情况下知道文件是否存在。并且,对于 PHP >= 5.3,您可以使用新的
GlobIterator
。As an example with `glob()`, the following portion of code :
给我这个输出:
While this one :
是的,有两个
*
;-)会给我:
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
.As an example with `glob()`, the following portion of code :
Gives me this output :
While this one :
Yes, with two
*
;-)Will give me :
从 PHP5.3 开始,您还可以使用
GlobIterator
使用通配符搜索目录:将返回数组中 some/path 中所有 .pdf 文件的完整路径。上面的执行方式与 glob() 大致相同,但迭代器提供了更强大且可扩展的 API。
As of PHP5.3, you can also use the
GlobIterator
to search a directory with wildcards: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.只要 file_exists 返回一个 BOOLEAN 我就写了这个小函数
接受带 * 的搜索字符串来查找文件...
例子:
As long as file_exists returns a BOOLEAN I wrote this small function
that accepts a search string with * to look for files...
Example:
如果您需要更多的控制并且使用 PHP 5.3 之前的版本,您可以使用 DirectoryIterator 或 RecursiveDirectoryIterator。两者都具有许多用于增加控制和操作的强大功能。
PHP 文档位于 DirectoryIterator 和 递归目录迭代器
If you need a little more control and are on pre PHP 5.3 you could use a DirectoryIterator or RecursiveDirectoryIterator. Both have a lot of great function for added control and manipulation.
PHP docs are at DirectoryIterator and RecursiveDirectoryIterator
您可以使用
fnmatch
将一个文件名与一种模式进行匹配。在所有文件上循环使用它。You can use
fnmatch
to match one filename against a pattern. Use this in a loop over all files.