php – RegEx – How To Insert String Before File Extension-ThrowExceptions

Exception or error:

How would I insert “_thumb” into files that are being dyanmically generated.

For example, I have a site that allows users to upload an image. The script takes the image, optimizes it and saves to file. How would I make it insert the string “_thumb” for the optimized image?

I’m currently saving 1 version of the otpimized file.

I want to save the original as the above string, but want to append, “_thumb” like the following string

How to solve:

No need to use regex. This will do it:

$extension_pos = strrpos($filename, '.'); // find position of the last dot, so where the extension starts
$thumb = substr($filename, 0, $extension_pos) . '_thumb' . substr($filename, $extension_pos);


Rather than take the regular expression route (or other crude string manipulation) perhaps some filename-related functions might be easier to live with: namely pathinfo (to get the file extension) and basename (to get the filename minus extension).

$ext   = pathinfo($filename, PATHINFO_EXTENSION);
$thumb = basename($filename, ".$ext") . '_thumb.' . $ext;

Edit: @tanascius sorry for the very similar answer, guess I should’ve checked the little pop-up whilst writing this (it took a while, I got distracted).


Why do you want to use a RegEx? Is the extension always .jpg and is there only one extension? Maybe you can replace it by _thumb.jpg?

If it is not that simple, you can use a function like pathinfo to extract the basename + extension and do a replace there. That is working without a regex, too, which might be overkill here:

$info = pathinfo( $file );
$no_extension =  basename( $file, '.'.$info['extension'] );
echo $no_extension.'_thumb.'.$info['extension']



I think that using a regexp is far more speed effective AND really better for

But I admit Chad’s solution is elegant and effective


Assuming you only have the occurrence of “.jpg” once in the string, you can do a str_replace instead of regex

$filename = str_replace(".jpg", "_thumb.jpg", $filename);

or even better, substr_replace to just insert the string somewhere in the middle:

$filename = substr_replace($filename, '_thumb', -4, 0);


$str = "ch-1268312613-photo.jpg";
print preg_replace("/\.jpg$/i","_thumb.jpg",$str);

Leave a Reply

Your email address will not be published. Required fields are marked *