0

So I am using directory iterator to get all php files like this:

$file_list = new RegexIterator($iterator_instance, '/^.+\.php$/');

Now $file_list contains all files having .php extension. However I want to be able to get all php files but skip folders with name view but I am not sure how to write such regex as I am not that good at it.

I just want to get all .php files but not from folder named views.


Update:

$dir_iterator = new RecursiveDirectoryIterator($path);
$iterator = new RecursiveIteratorIterator($dir_iterator);
$file_list = new RegexIterator($iterator, '/^.+\.php$/');
// foreach stuff now

Here I just want that from returned file/folder names, a folder named views should be skipped and I would love if above regex can be modified to account for that as well.

2 Answers 2

4

You could use a CallbackFilterIterator (PHP 5.4)

// Assuming $file_list is based on a FilesystemIterator
$iter = new CallbackFilterIterator($file_list, function($current) {
    return strpos('/views/', $current->getReaPath()) === false;
});

For PHP 5.3:

class DirectoryFilter extends FilterIterator {
    public function accept() {
        $current = $this->getInnerIterator()->current();
        return strpos('/views/', $current->getReaPath()) === false;
    }
}
$iter = new DirectoryFilter($file_list);
Sign up to request clarification or add additional context in comments.

3 Comments

That's not my question ! I know that. It is about regex and skipping folder named views while using RegexIterator eg regex
@Dev555 I indeed mis read your problem. I have updated my answer again.
Thanks for your answer I was preferably looking for regex solution. +1 though.
3

You can use this regex:

'%^(?!.*[\\\\/]views?[\\\\/]).+\.php$%'

Explanation:

^         # Start of string
(?!       # Assert that it's impossible to match the following here:
 .*       #  any number of characters
 [\\\\/]  #  a path delimiter (backslash or forward slash)
 views?   #  followed by view or views
 [\\\\/]  #  followed by a path delimiter
)         # End of lookahead assertion
.+        # Match one or more characters
\.php     # Match .php
$         # End of string

4 Comments

It isn't working when i run through updated code in my question. I am still getting views folder and files under it.
In your original question, the folders you wanted to skip were named view, not views. If you want to catch both, use /views?/ in the lookahead assertion.
Thanks but it sill returns views folder. An example: admin\views\includes\footer.php. I want all php files but not from views folder that's actually want i am looking for.
OK, this regex matches / as path delimiters, you're using `\`. No problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.