문제

I need to find a file in a directory that matches a certain condition. For example, I know the file name starts with '123-', and ends with .txt, but I have no idea what is in between the two.

I've started the code to get the files in a directory and the preg_match, but am stuck. How can this be updated to find the file I need?

$id = 123;

// create a handler for the directory
$handler = opendir(DOCUMENTS_DIRECTORY);

// open directory and walk through the filenames
while ($file = readdir($handler)) {

  // if file isn't this directory or its parent, add it to the results
  if ($file !== "." && $file !== "..") {
    preg_match("/^".preg_quote($id, '/')."\\-(.+)\\.txt$/" , $file, $name);

    // $name = the file I want
  }

}

// tidy up: close the handler
closedir($handler);
도움이 되었습니까?

해결책

I wrote up a little script here for ya, Cofey. Try this out for size.

I changed the directory for my own test, so be sure to set it back to your constant.

Directory Contents:

  • 123-banana.txt
  • 123-extra-bananas.tpl.php
  • 123-wow_this_is_cool.txt
  • no-bananas.yml

Code:

<pre>
<?php
$id = 123;
$handler = opendir(__DIR__ . '\test');
while ($file = readdir($handler))
{
    if ($file !== "." && $file !== "..")
    {
      preg_match("/^({$id}-.*.txt)/i" , $file, $name);
      echo isset($name[0]) ? $name[0] . "\n\n" : '';
    }
}
closedir($handler);
?>
</pre>

Result:

123-banana.txt

123-wow_this_is_cool.txt

preg_match saves its results to $name as an array, so we need to access by it's key of 0. I do so after first checking to make sure we got a match with isset().

다른 팁

You must test if the match was successful.

Your code inside the loop should be this:

if ($file !== "." && $file !== "..") {
    if (preg_match("/^".preg_quote($id, '/')."\\-(.+)\\.txt$/" , $file, $name)) {
        // $name[0] is the file name you want.
        echo $name[0];
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top