Stickers
Stickers

Reputation: 78686

Remove image extension, rename and restore

Say the image is called:gecko.jpg

Can I first remove ".jpg" and add "-100x100" after "gecko", and then put the extension back, so it would be "gecko-100x100.jpg"?

Upvotes: 2

Views: 4500

Answers (2)

goat
goat

Reputation: 31813

use pathinfo

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

Upvotes: 5

Michael Berkowski
Michael Berkowski

Reputation: 270637

Yes, quite simply with PHP's string functions in conjunction with basename()

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

Or to do it with any filetype using strrpos() to locate the extension by finding the last .

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

Upvotes: 4

Related Questions