Following a given example by a comment in the php.net manual I am trying to grab each file named file.txt in a recursively directory structure.
Folder/
subfold1
subfold2
file.txt
subfold3
file.txt
etc. is a example on how the folder structure may look like.
$directory = new \RecursiveDirectoryIterator(__DIR__ . '/..');
$iterator = new \RecursiveIteratorIterator($directory);
$files = new \RegexIterator($iterator, '/^file.txt$/', \RecursiveRegexIterator::GET_MATCH);
var_dump($files);
The problem is that the given code is giving the following result:
object(RegexIterator)#4 (1) { ["replacement"]=> NULL }
What should I do with it? I am simply looking for the file and the given path, preferably in an array.
You generally want to iterate over the
*Iterator
object, most often using a basicforeach()
loop.In your case, the work is a little more involved because the code that you are using at the moment will never return any matching files to iterate. First, let's see what should work.
The key take-home changes are:
RecursiveDirectoryIterator::KEY_AS_FILENAME
flag for theRecursiveDirectoryIterator
, used in combination withRegexIterator::USE_KEY
flag for the RegexIterator`Previously, as the iterator was being iterated, the regex would be matching against the "current" iterator value which in your case was an
SplFileInfo
object representing each file. When cast to a string, for the regex to do its matching, theSplFileInfo
objects were turned into their full path; directories and all. This meant that your regex would never match since it is only expecting the file name.To cut a long story short, the
KEY_AS_FILENAME
andUSE_KEY
flags mean that the regex is working on just the file name for each file. Yay!You may also notice that I have used the
RegexIterator
inRegexIterator::MATCH
mode. This means that upon looping over the matched files, we have full access to eachSplFileInfo
object. This gives us much more to play with than just a string with the file name asRegexIterator::GET_MATCH
would provide.To print out each of the files, with their full paths, you could use something like:
See the
SplFileInfo
documentation for a full list of methods available.