Wil*_*rth 20 php directory recursion filenames
我试图用PHP列出目录中的文件(递归或非),其中filename匹配某种模式.我对正则表达式的态度从未如此强大,所以你能提供的任何帮助都会很棒.我可以搜索返回的文件名的文字检查,但我认为这不是一个好主意:)
更新+最终解决方案:2011年1月18日晚上8:06
一旦我理解了正则表达式,我找到了另一种方法来做我想要的东西.我完全对我在正则表达式中的位置感到沮丧,我现在得到了一些感谢,感谢一位朋友将我拉到一边用比在线指南中找到的更简单的术语解释一些.
此解决方案基本上检查具有前缀"prefixone"或"prefixtwo"的特定图像,同时还验证它是某种类型的图像(jpg,jpeg,png)并匹配以下任何格式.
根据您从Wordpress传递的slug(我使用它的地方),它将与该正则表达式匹配.以下是一个示例列表:
prefixone.123-abc._tag1.001.jpg
prefixone.345-xyz._tag1.002.jpeg
prefixtwo.123-abc._tag2._tag1.003.jpg
prefixone.123-abc._tag2.004.jpeg
prefixtwo.345-xyz._tag2._tag3._tag1.005.jpg
prefixtwo.123-abc._tag1.001.jpg
prefixone.345-xyz._tag1.001.png
prefixtwo.456-rst._tag1.001.png
Run Code Online (Sandbox Code Playgroud)
所有这些文件可能已经从我们的opendir()函数返回到文件列表中,如果slug匹配,这些文件中的任何一个都可能匹配.无论文件名中标记信息的顺序如何.
我希望这有助于其他用户与正则表达式斗争.掌握这一点是一件痛苦的经历,但是一旦你理解了一些基本的东西,其余的就会迅速开始建立你自己的东西.
码:
<?php
// create an array to hold directory list
$results = array();
// create a handler for the directory
$directory = $_SERVER['DOCUMENT_ROOT'].'/some/path/to/images/';
$handler = opendir($directory);
// open directory and walk through the filenames
while ($file = readdir($handler)) {
// if file isn't this directory or its parent, add it to the results
if ($file != "." && $file != "..") {
// check with regex that the file format is what we're expecting and not something else
if(preg_match('#^(prefixone|prefixtwo)[^\s]*\.'.$wordpress-slug.'\.[^\s]+(\.(jpg|jpeg|png))#', $file)) {
// add to our file array for later use
$results[] = $file;
}
}
}
?>
Run Code Online (Sandbox Code Playgroud)
我实际上并不需要递归,但在网上确实存在大量的递归示例,这确实是我最不担心的问题.按模式进行内容隔离是此任务的核心,因此上述代码已足够.
边注:
对于那些昨天指出"接受的评论"的人,我不知道我错过了那个而且我道歉.我过得很糟糕.对不起,如果我似乎对任何人发表评论.这是一个很棒的社区,我很乐意尽我所能回馈.
Gor*_*don 15
使用glob找到匹配的文件路径模式或GlobIterator.
如果你需要递归使用a RegexIterator和a RecursiveDirectoryIterator.
标记此CW因为问题确实重复,您可以在使用搜索功能时轻松找到上述所有示例.请这样做.
| 归档时间: |
|
| 查看次数: |
39244 次 |
| 最近记录: |