如何在php中使用glob()返回文件名

[英]How to return just file name using glob() in php


How can I just return the file name. $image is printing absolute path name?

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

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

All I want is the file name in the specific directory not the absolute name.

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

7 个解决方案

#1


17  

Instead of basename, you could chdir before you glob, so the results do not contain the path, e.g.:

你可以在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;
?>

This is probably a little faster, but won't make any significant difference unless you have tons of files

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

#2


38  

Use php's basename

使用php的basename

Returns trailing name component of path

返回路径的尾随名称组件

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

#3


11  

Use basename()

echo basename($image);

You can also remove the extension like this:

你也可以删除这样的扩展名:

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

#4


11  

One-liner:

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

#5


1  

Take a look at pathinfo

看看pathinfo

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

Pretty helpful function

非常有用的功能

#6


0  

Example extracting only file names and converting in new array of filenames width extension.

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

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

#7


0  

If you're nervous about the unintended consequences of changing the working directory, you can store the current dir with getcwd() before changing, then simply use that value to switch back after you've done everything you need to do in that dir.

如果您对更改工作目录的意外后果感到紧张,可以在更改之前使用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);
  ?>

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/01/16/c0beae8878f24e370426eec5d875f6cc.html



 
  © 2014-2022 ITdaan.com 联系我们: