Richard Allsopp
Richard Allsopp

Reputation: 37

Recursive Directory Searching PHP with Regex

beWhat if I needed to recursively search some directories in order to find a .something file?

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.

e.g. I want to say find all the filesnames that contain "hello" and end in .apk.

With Glob() i did this which worked great:

glob('./'path'/*{'Hello'}*.apk',GLOB_BRACE);

However its not recursive. and depends on the correct directory being specified. Any help would much appreciated.

Upvotes: 1

Views: 1219

Answers (3)

Salman Arshad
Salman Arshad

Reputation: 272256

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:

if (strpos($filename, 'hello') !== false && substr($filename, -4) === '.apk')

Upvotes: 1

flu
flu

Reputation: 14693

Instead of strpos() you can use a regular expression like:

[...]
if(preg_match('/.*hello.*\.apk$/', $filename))
[...]

This example represents "*hello*.apk". So a string that has "hello" somewhere in it and ends with ".apk".

See PHP preg_match() for further information.

Upvotes: 2

periklis
periklis

Reputation: 10188

Try searching both:

if(strpos($filename, ".apk") !== false && strpos($filename, "Hello") !== false){

The !== false is necessary, otherwise Hello.apk will not be returned

Upvotes: 0

Related Questions