【问题标题】:How to return just file name using glob() in php如何在 php 中使用 glob() 只返回文件名
【发布时间】:2012-12-31 06:35:41
【问题描述】:

我怎样才能只返回文件名。 $image 正在打印绝对路径名?

<?php
$directory = Yii::getPathOfAlias('webroot').'/uploads/';
$images = glob($directory . "*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE);
 foreach($images as $image)
   echo $image
?>

我想要的只是特定目录中的文件名而不是绝对名称。

【问题讨论】:

    标签: php yii


    【解决方案1】:

    使用php的basename

    返回路径的尾随名称组件

    <?php
    $directory = Yii::getPathOfAlias('webroot').'/uploads/';
    $images = glob($directory . "*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE);
     foreach($images as $image)
       echo basename($image);
    ?>
    

    【讨论】:

      【解决方案2】:

      您可以在 glob 之前使用 chdir 代替 basename,因此结果不包含路径,例如:

      <?php
      $directory = Yii::getPathOfAlias('webroot').'/uploads/';
      chdir($directory); // probably add some error handling around this
      $images = glob("*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE);
       foreach($images as $image)
         echo $image;
      ?>
      

      这可能会快一点,但除非您有大量文件,否则不会有任何显着差异

      【讨论】:

        【解决方案3】:

        单线:

        $images = array_map('basename', glob($directory . "*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE));
        

        【讨论】:

          【解决方案4】:

          使用basename()

          echo basename($image);
          

          您也可以像这样删除扩展:

          echo basename($image, '.php');
          

          【讨论】:

            【解决方案5】:

            看看路径信息

            http://php.net/manual/en/function.pathinfo.php

            非常有用的功能

            【讨论】:

              【解决方案6】:

              如果您对更改工作目录的意外后果感到紧张,您可以在更改之前使用getcwd() 存储当前目录,然后在完成您需要做的所有事情后简单地使用该值切换回来那个目录。

                <?php
                $directory = Yii::getPathOfAlias('webroot').'/uploads/';
                $working_dir = getcwd();
                chdir($directory);
                $files = glob("*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE);
                chdir($working_dir);
                ?>
              

              【讨论】:

                【解决方案7】:

                示例仅提取文件名并转换为新的文件名数组宽度扩展。

                $dir =  get_stylesheet_directory();//some dir - example of getting full path dir in wordpress
                $filesPath = array_filter(glob($dir . '/images/*.*'), 'is_file');
                
                $files = array();       
                foreach ($filesPath as $file) 
                {
                   array_push($files, basename($file));
                }
                

                【讨论】:

                  猜你喜欢
                  • 2010-12-04
                  • 1970-01-01
                  • 2011-07-02
                  • 2015-10-19
                  • 1970-01-01
                  • 1970-01-01
                  • 2021-07-18
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多