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

2019-02-11 14:14发布

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

<?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.

标签: php yii
7条回答
仙女界的扛把子
2楼-- · 2019-02-11 14:47

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

<?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

查看更多
Luminary・发光体
3楼-- · 2019-02-11 14:47

Take a look at pathinfo

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

Pretty helpful function

查看更多
beautiful°
4楼-- · 2019-02-11 14:53

Use basename()

echo basename($image);

You can also remove the extension like this:

echo basename($image, '.php');
查看更多
5楼-- · 2019-02-11 14:54

One-liner:

$images = array_map('basename', glob($directory . "*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE));
查看更多
爷、活的狠高调
6楼-- · 2019-02-11 15:00

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楼-- · 2019-02-11 15:03

Use php's 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);
?>
查看更多
登录 后发表回答