Hi.
I use the following function to rename thumbnails.
For example, if I upload a file called "image.png" to an upload folder, and this folder already has a file named "image.png" in it, the new file automatically gets renamed to "image-copy-1.png". If there also is a file called "image-copy-1.png" it gets renamed to "image-copy-2.png" and so on.
The following function returns the new filename. At least that's what it is supposed to do...
The renaming doesn't seeem to work correctly, though. Sometimes it produces strange results, like: (I always uploaded a file named "1.png")
1-copy-1.png
1-copy-2.png
1-copy-2-copy-1.png
1-copy-2-copy-3.png
I hope you understand my problem, despite my description being somewhat complex... Can you tell me what went wrong here? (bonus question: Is regular expressions the right tool for doing this kind of stuff?)
<?php
function renameDuplicates($path, $file)
{
$fileName = pathinfo($path . $file, PATHINFO_FILENAME);
$fileExtension = "." . pathinfo($path . $file, PATHINFO_EXTENSION);
if(file_exists($path . $file))
{
$fileCopy = $fileName . "-copy-1";
if(file_exists($path . $fileCopy . $fileExtension))
{
if ($contains = preg_match_all ("/.*?(copy)(-)(\\d+)/is", $fileCopy, $matches))
{
$copyIndex = $matches[3][0];
$fileName = substr($fileCopy, 0, -(strlen("-copy-" . $copyIndex))) . "-copy-" . ($copyIndex + 1);
}
}
else
{
$fileName .= "-copy-1";
}
}
$returnValue = $fileName . $fileExtension;
return $returnValue;
}?>