[英]Recursive Directory Searching PHP with Regex
beWhat if I needed to recursively search some directories in order to find a .something file? 如果我需要递归搜索某些目录以便找到.something文件,该怎么办?
I have this code so far: 到目前为止我有这个代码:
$dir_iterator = new RecursiveDirectoryIterator('path/');
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $filename) {
if(strpos($filename, ".apk")){
$page->addToBody(substr($filename, 2)."</br>");
$filename = substr($filename, 2);
}
}
This works in returning the only .apk file in the directories, however I want to be able to find a specific file if more than one are found. 这适用于返回目录中唯一的.apk文件,但是如果找到多个文件,我希望能够找到特定文件。
eg I want to say find all the filesnames that contain "hello" and end in .apk. 例如,我想说找到包含“hello”的所有文件名,并以.apk结尾。
With Glob() i did this which worked great: 使用Glob()我做了这个很棒的工作:
glob('./'path'/*{'Hello'}*.apk',GLOB_BRACE);
However its not recursive. 但它不是递归的。 and depends on the correct directory being specified. 并取决于指定的正确目录。 Any help would much appreciated. 任何帮助将非常感谢。
Instead of strpos() you can use a regular expression like: 您可以使用正则表达式代替strpos(),而不是:
[...]
if(preg_match('/.*hello.*\.apk$/', $filename))
[...]
This example represents "*hello*.apk". 此示例表示“* hello * .apk”。 So a string that has "hello" somewhere in it and ends with ".apk". 所以一个字符串在其中某处有“hello”并以“.apk”结尾。
See PHP preg_match() for further information. 有关详细信息,请参阅PHP preg_match() 。
Change the line: 换行:
if(strpos($filename, ".apk"))
To: 至:
if (preg_match('@hello.*\.apk$@', $filename))
While regular expressions are more flexible, you can still use strpos
along with substr
: 虽然正则表达式更灵活,但您仍然可以使用strpos
和substr
:
if (strpos($filename, 'hello') !== false && substr($filename, -4) === '.apk')
Try searching both: 尝试搜索两个:
if(strpos($filename, ".apk") !== false && strpos($filename, "Hello") !== false){
The !== false is necessary, otherwise Hello.apk will not be returned !== false是必要的,否则将不会返回Hello.apk
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.