如何在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 联系我们: