2012-12-07 4 views
0

특정 조건과 일치하는 디렉토리에서 파일을 찾아야합니다. 예를 들어 파일 이름이 '123- '로 시작하고 .txt로 끝나는 것을 알고 있지만 두 파일 사이에 무엇이 있는지 전혀 알 수 없습니다.preg_match를 사용하여 디렉토리에서 파일을 찾으십니까?

디렉토리와 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); 
+0

다음을 사용하십시오 :'/^(123 -. *. txt)/i'; 파일 이름과 일치합니다. 중간에 .125로 시작하고 .txt로 끝납니다. – phpisuber01

답변

3

나는 Cofey, 나중에 여기 약간의 스크립트를 썼습니다. 크기에 대해이 방법을 사용해보십시오.

내 자신의 테스트를 위해 디렉토리를 변경 했으므로 상수로 다시 설정해야합니다.

디렉토리 내용 :

  • 123 banana.txt
  • 123 여분 bananas.tpl.php
  • 123 wow_this_is_cool.txt
  • 없는 bananas.yml

코드 :

결과 6,
<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()와 일치합니다.

1

일치가 성공했는지 테스트해야합니다. 루프 내부

코드는 다음과 같아야합니다

if ($file !== "." && $file !== "..") { 
    if (preg_match("/^".preg_quote($id, '/')."\\-(.+)\\.txt$/" , $file, $name)) { 
     // $name[0] is the file name you want. 
     echo $name[0]; 
    } 
} 
관련 문제