用readdir选择文件

时间:2012-06-15 18:33:11

标签: php readdir

<?php
// open the current directory
$dhandle = opendir('.');
// define an array to hold the files
$files = array();

if ($dhandle) {
   // loop through all of the files
   while (false !== ($fname = readdir($dhandle))) {

      if (($fname != 'other') && ($fname != 'dd') && ($fname != 'index.htm') && ($fname != 'torcache.php')&& ($fname != 'error_log') && 
          ($fname != basename($_SERVER['PHP_SELF']))) {
          // store the filename
          $files[] = (is_dir( "./$fname" )) ? "(Dir) {$fname}" : $fname;
      }
   }
   // close the directory
   closedir($dhandle);
}

我想要做的是,如果文件以'other'或'dd'开头,那么不要将它包含在循环$ files中;如果没有在!=中命名整个文件名,我该怎么办才能排除这些文件?

1 个答案:

答案 0 :(得分:4)

将此添加到您的支票中:

(substr($fname, 0, 5) != 'other') && (substr($fname, 0, 2) != 'dd')

PHP substr。它接受一个字符串,并从给定的第一个数字开始返回一个子字符串(0表示字符串的开头),第二个数字给出一个长度(5为“other”和2为“dd”)。

所以你的完整陈述将是:

if (
    (substr($fname, 0, 5) != 'other') &&
    (substr($fname, 0, 2) != 'dd') &&
    ($fname != 'index.htm') &&
    ($fname != 'torcache.php') &&
    ($fname != 'error_log') &&
    ($fname != basename($_SERVER['PHP_SELF']))
) { ... }
相关问题