0

Hi i have stored some file names in mongodb and i stored some files in my local directory, now my requirement is to extract the local path of the file which matches to the value in the db exactly it should not match a particular string in the file it should match with complate string. can u please suggest me how to do this.

example: sample-php-book.pdf is the db value it should match with sample-php-book.pdf file name not with sample.pdf

i have used the following code

<?php
$results = array();
$directory = $_SERVER['DOCUMENT_ROOT'].'/some/path/to/files/';
$handler = opendir($directory);

while ($file = readdir($handler)) {

        if(preg_match('$doc['filename']', $file)) {

            $results[] = $file;
        }
    }
}
?>

$doc[filename] is the value from db

Thanks

user2353439
  • 489
  • 2
  • 7
  • 18
  • http://php.net/manual/en/function.strcmp.php for comparison. http://stackoverflow.com/questions/6155533/loop-code-for-each-file-in-a-directory for looping thru directory. Or did I missunterstood you? – Chris May 29 '13 at 11:20
  • http://stackoverflow.com/questions/3321547/help-using-regexiterator-in-php – Rajeev Ranjan May 29 '13 at 11:27

1 Answers1

0

If I understand you correctly than you are looking for something like this:

Edit: I somehow forgot that split uses regex instead of a simple search. Therefore I replaced split with explode

<?php

// DB-Code here[..]

$arrayWithYourDbStrings; // <-- should conatain all strings you obtained from the db

$filesInDir = scandir('files/');
foreach($filesInDir as $file)
{
    // split at slash
    // $file = split('/', $file); <-- editted
    $file = explode('/', $file);

    // get filename without path
    $file = last($file);

    // check if filename is in array
    if(in_array($file, $arrayWithYourDbStrings))
    {
        // code for match
    }
    else
    {
        // code for no match
    }
}
?>
Chris
  • 661
  • 2
  • 7
  • 23
  • sorry,it's not working for me. it not going into if(in_array($file, $doc['filename'])) loop – user2353439 May 29 '13 at 11:57
  • @user2353439 According to your Code above you don't have an array with all the string from the database. Are you sure you passing in an array as a second parameter for in_array();? – Chris May 29 '13 at 12:05
  • i have stored all my db values in a variable like this $result = $db->$mydb->$mycollection->find(array('filename = new MongoRegex('/sample.pdf/') then i used for loop like this foreach($result as $doc) then followed ur procedure... – user2353439 May 29 '13 at 12:19
  • @user2353439 Then you have to change `in_array($file, $arrayWithYourDbStrings)` with a simple string compare `strcmp($file, $doc)`. – Chris May 29 '13 at 12:24
  • thanks for that but i am getting function split and last() are deprecated – user2353439 May 29 '13 at 12:38
  • @user2353439 Check out my edit. I mixed split() and explode(). You should use explode() instead of split(). – Chris May 29 '13 at 13:33