This is fast and can correct to show it,
/**
* 增加後綴字至檔名後方
* Add suffix to a file name
*
* @example suffixFileName("test.tar.gz", '_new'); //it will retrun "test.tar_new.gz"
* @version 2023.06.20 Jwu
* @param string $fullPath filename
* @param string $suffix insert String Before File Extension
*
* @return string new file path
*/
function suffixFileName($fullPath, $suffix = "_thumb"){
$pos = strrpos($fullPath, ".");
if(substr($fullPath, -1) == '.'){
$pos = strrpos(substr($fullPath, 0, $pos), ".");
}
if ($pos === false) {
return $fullPath . $suffix;
}
//$filenameWithoutExt = substr($fileName, 0, -(strlen($pos) + 2));
return substr_replace($fullPath, $suffix, $pos, 0);
}
Test Demo:
// Unit Test
function output($n){
print_r($n);
print_r('<br>');
print_r(suffixFileName($n, "_thumb"));
print_r('<hr>');
}
$testFiles = array(
'C:\Jwu\TestPictures\sample.jpg',
'http://Jwu/TestPictures/sample.jpg',
'TestPictures\this.is.a.jpg',
'sample.tar.gz',
'1.jpg',
'.jpg',
'recent.image.jpg.',
'image.gift.1234.gif'
);
array_map('output', $testFiles);
Output:
C:\Jwu\TestPictures\sample.jpg
C:\Jwu\TestPictures\sample_thumb.jpg
http://Jwu/TestPictures/sample.jpg
http://Jwu/TestPictures/sample_thumb.jpg
TestPictures\this.is.a.jpg
TestPictures\this.is.a_thumb.jpg
sample.tar.gz
sample.tar_thumb.gz
1.jpg
1_thumb.jpg
.jpg
_thumb.jpg
recent.image.jpg.
recent.image_thumb.jpg.
image.gift.1234.gif
image.gift.1234_thumb.gif