tags:

views:

49

answers:

2
$config['file_name'] = preg_replace('/(\.gif|\.jpg|\.png)/', '_thumb$1', $filename);

Basically I want filename.jpg to become filename_thumb.jpg

I don't understand why but the extension is being repeated twice. (filename.jpg.jpg).

Edit This does work, I have other problems in my code.

+2  A: 

Should work.

echo preg_replace('/(\.gif|\.jpg|\.png)/', '_thumb$1', "filename.jpg");

gives filename_thumb.jpg.

In any case, use the expression '/(\.gif|\.jpg|\.png)$/' instead (better, don't use parentheses and replace $1 with $0), so that it only matches the string if it's on the end.

Artefacto
without parentheses he will be not able to specify $ without copy-pasting it for each extension
zerkms
@zerkms Good point. But he can use `(?:)` instead. There's really no need to use a capture group.
Artefacto
+2  A: 

The best way to do it would probably be...

$filename_ext = pathinfo($filename, PATHINFO_EXTENSION);

$filename = preg_replace('/^(.*)\.' . $filename_ext . '$/', '$1_thumb.' . $filename_ext, $filename);

I justed tested it, with $filename = 'path/to/something.jpg'; and the output was path/to/something_thumb.jpg.

I say the best way because generally using PHP's inbuilt functions are better. This also allows for all file extensions that PHP can handle (being string splitting, it should be all).

alex
What about extensions that contain characters that have meaning in regular expressions?..
Artefacto
@Artefacto True, [but which ones do](http://www.regular-expressions.info/reference.html)? Can't think of any of the top of my head... I'm sure there are some edge cases though.
alex
I already have a check for that before this snippet runs.
Keyo
@Artefacto I just thought of `tar.gz`... [PHP returns](http://codepad.org/9FtqvjXn) `gz` only. So I guess that might not be correct from an extension point of view, but correct if finding characters following the last occurrence of a period.
alex
For instance, `[` and `]`.
Artefacto
@Artefacto Which extensions contain brackets though?
alex
@alex how is `gz` not correct for a file named `foo.tar.gz`; is it not a gzipped file?
salathe