tags:

views:

87

answers:

6

Hi All,

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

A: 

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']
tanascius
+1  A: 

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);
Chad Birch
A: 
$str = "ch-1268312613-photo.jpg";
print preg_replace("/\.jpg$/i","_thumb.jpg",$str);
ghostdog74
A: 
 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

Darkyo
There are a couple things wrong with this. You didn't escape the period in the pattern, so that will match any character at all. Also, `\w` does not cover all possible filename characters.
Chad Birch
True, because I didn't mark it as code so \. was interpreted like . And True again but does the filesystem has the right to use any char, I bet no
Darkyo
A: 

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);
Andy E
A: 

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

salathe