Add suffix to file name

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

I basically want to filename.jpgbecomefilename_thumb.jpg

I do not understand why, but the extension is repeated twice. (Filename.jpg.jpg).

Change . This works, I have other problems in my code.

+3
source share
3 answers

Must work.

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

gives filename_thumb.jpg.

In any case, use an expression instead '/(\.gif|\.jpg|\.png)$/'(better, do not use parentheses and do not replace $ 1 with $ 0), so that it will only match the string if it is at the end.

+5
source

The best way to do this is likely to be ...

$filename_ext = pathinfo($filename, PATHINFO_EXTENSION);

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

I tried to test it, with $filename = 'path/to/something.jpg';, but the result was path/to/something_thumb.jpg.

, PHP. , PHP ( , ).

+10

Perhaps it would be better to use PHP in build methods such as pathinfoand basename. it will process all children's files, including without extension

$extension = pathinfo($filename, PATHINFO_EXTENSION);
$baseName = basename($filename, ".{$extension}");
$newName = "{$baseName}_thumb.{$extension}";
0
source

Source: https://habr.com/ru/post/1757947/


All Articles