Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add suffix to a file name

Tags:

regex

php

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

like image 955
Keyo Avatar asked Dec 02 '22 05:12

Keyo


2 Answers

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

like image 163
alex Avatar answered Dec 09 '22 11:12

alex


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.

like image 29
Artefacto Avatar answered Dec 09 '22 12:12

Artefacto