Search code examples
phpstringfilenames

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


Solution

  • 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