RegEx - How To Insert String Before File Extension

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. ch-1268312613-photo.jpg

I want to save the original as the above string, but want to append, "_thumb" like the following string ch-1268312613-photo_thumb.jpg

Answers


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']

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);

 preg_replace("/(\w+)\.(\w+)/","'\\1_thumb.\\2'","test.jpg"); 

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

But I admit Chad's solution is elegant and effective


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

Need Your Help

Can I change the name of `nohup.out`?

bash logging nohup

When I run nohup some_command &, the output goes to nohup.out; man nohup says to look at info nohup which in turn says:

How to send list of Objects to View and back to Post method in controller

java spring-mvc post

Suppose I have class Person, I made a list of Person instances and add this list to a Model.