删除图片扩展名,重命名和还原

时间:2011-12-04 20:04:37

标签: php string filenames

假设图像被调用:gecko.jpg

我可以先删除“.jpg”并在“gecko”之后添加“-100x100”,然后将扩展名放回去,那么它将是“gecko-100x100.jpg”吗?

2 个答案:

答案 0 :(得分:5)

使用pathinfo

$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');
$new = $path_parts['filename'] . '-100x100.' .$path_parts['extension'];

答案 1 :(得分:4)

是的,非常简单地将PHP的字符串函数与basename()

结合使用
$base = basename($filename, ".jpg");
echo $base . "-100x100" . ".jpg";

或者使用strrpos()使用任何文件类型来查找扩展名.

// Use strrpos() & substr() to get the file extension
$ext = substr($filename, strrpos($filename, "."));
// Then stitch it together with the new string and file's basename
$newfilename = basename($filename, $ext) . "-100x100" . $ext;

-

// Some examples in action...
$filename = "somefile.jpg";
$ext = substr($filename, strrpos($filename, "."));
$newfilename = basename($filename, $ext) . "-100x100" . $ext;
echo $newfilename;
// outputs somefile-100x100.jpg

// Same thing with a .gif
$filename = "somefile.gif";
// outputs somefile-100x100.gif