PHP 列出目录中的文件并删除扩展名


Php list files in a directory and remove extention

我用这个php代码来检索存储在目录中的文件。

if ($handle = opendir('FolderPath')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            echo "$entry'n <br />" ; 
        }
    }
    closedir($handle);
}

此目录仅包含PHP文件,我如何能够从回显结果中删除扩展名? 示例:(index.php会变得index

最简单的

方法是使用 glob 函数:

foreach (glob('path/to/files/*.php') as $fileName) {
    //extension .php is guaranteed here
    echo substr($fileName, 0, -4), PHP_EOL;
}

这里glob的优点是您可以消除那些讨厌的readdiropendir电话。唯一轻微的"不满意"$fileName的值也将包含路径。但是,这是一个简单的解决方法(只需添加一行):

foreach (glob('path/to/files/*.php') as $fullName) {
    $fileName = explode('/', $fullName);
    echo substr(
        end($fileName),//the last value in the array is the file name
        0, -4),
    PHP_EOL;
}

这应该适合您:

echo basename($entry, ".php") . "'n <br />" ; 

一个快速的方法是

<?php
 if ($handle = opendir('FolderPath')) {
    while (false !== ($file = readdir($handle))) {
      if ($file != "." && $file != "..") {
          $info = pathinfo($file);
          $file_name =  basename($file,'.'.$info['extension']);
          echo $file_name;
     }
    }
   closedir($handle);

?>

$files = glob('path/to/files/*.*');
foreach($files as $file) {
  if (! is_dir($file)) {
    $file = pathinfo($file);
    echo "<br/>".$file['filename'];
  }
}

使用 pathinfo()

$entry = substr($entry, 0, strlen($entry) - 4);

请注意,这是一个简单快速的解决方案,如果您 100% 确定您的扩展是 *.xxx 的形式,则可以完美运行。但是,如果您需要一个更灵活、更安全的解决方案来处理可能的不同扩展长度,则不建议使用此解决方案。

优雅的解决方案是使用DirectoryIterator::getBasename()方法的$suffix属性。提供后,$suffix将在每次调用时删除。对于已知扩展,可以使用:

foreach (new DirectoryIterator('/full/dir/path') as $file) {
  if ($file->isFile()) {
    print $file->getBasename('.php') . "'n";
  }
}

或者这个,作为一个通用的解决方案:

foreach (new DirectoryIterator('/full/dir/path') as $file) {
  if ($file->isFile()) {
    print $file->getBasename($file->getExtension() ? '.' . $file->getExtension() : null) . "'n";
  }
}

PHP 文档:http://php.net/manual/en/directoryiterator.getbasename.php