1

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.

1
  • Hmz... 1. If you are on a linux machine, you can take advantage of the os functions! 2. If there's a directory called "hello" should all files within be returned? 3. You said regex, but your code uses strpos. Which do you actually want/need? Commented Jan 11, 2013 at 15:38

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

So could you add extra search fields to the regular expression? e.g. find a file name that has hello, abc, test and ends in .apk.
1

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')

Comments

0

Try searching both:

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

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

Comments

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.