0

特定の条件に一致するディレクトリ内のファイルを見つける必要があります。たとえば、ファイル名が「123-」で始まり、.txt で終わることは知っていますが、2 つの間に何があるかはわかりません。

ディレクトリ内のファイルと preg_match を取得するコードを開始しましたが、スタックしています。必要なファイルを見つけるためにこれを更新するにはどうすればよいですか?

$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);
4

2 に答える 2

3

Cofeyさんのためにここに小さなスクリプトを書きました。サイズについてはこれを試してみてください。

自分でテストするためにディレクトリを変更したので、必ず定数に戻してください。

ディレクトリの内容:

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

コード:

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

結果:

123-banana.txt

123-wow_this_is_cool.txt

preg_match結果を配列として保存する$nameため、キー0でアクセスする必要があります。最初に。と一致することを確認した後でアクセスしますisset()

于 2012-12-07T19:43:36.543 に答える
1

一致が成功したかどうかをテストする必要があります。

ループ内のコードは次のようになります。

if ($file !== "." && $file !== "..") {
    if (preg_match("/^".preg_quote($id, '/')."\\-(.+)\\.txt$/" , $file, $name)) {
        // $name[0] is the file name you want.
        echo $name[0];
    }
}
于 2012-12-07T19:26:37.720 に答える