I was aiming for something clean, but there is a small problem about renaming the first version.
This also doesn’t leave an original someName. Everything would return someName_1 and so on.
It probably needs a check incase there is no . in the file name.
[php]
$VERSION_SEPARATOR = ‘_’;
$EXTENSION_SEPARATOR = ‘.’;
function getNextFileVersion( $fileName, $toDirectory )
{
$toDirector = dirname($toDirector) . DIRECTORY_SEPARATOR;
$versionPos = strrpos( $fileName, $VERSION_SEPARATOR);
$extensionPos = strrpos( $fileName, $EXTENSION_SEPARATOR, $versionPos);
if( $versionPos > 0 )
{
$version = substr($fileName, $versionPos + 1, $versionPos + $extensionPos - 1);
}
$iCantThinkofABetterNameForARandomHack = ‘’;
if( false == is_numeric( $version ) )
{
$version = 1;
$versionPos = $extensionPos;
$iCantThinkofABetterNameForARandomHack = $VERSION_SEPARATOR;
}
$name = substr($fileName, 0, $versionPos);
$ext = substr($fileName, extensionPos) . $iCantThinkofABetterNameForARandomHack;
while( file_exists( $toDirector . $name . $version . $ext )
{
$version++;
}
return $name . $version . $ext;
}
- Edit a little bit later
I was hoping to add a track back to Mark, but it didn’t work the first time….
-= Comments
1. Mark | August 3rd, 2006 at 10:53 am
hmm, so that’s what a real programmers code looks like..
I still prefer the explodes / implodes to break into arrays.. rather than using substrings - I guess it’s just personal preference.
I really like this part.. It makes the looping part of the code very small. It’s a little more readable too with good variable names as opposed to my obscure arrays $file_name_parts and $file_name_inner_parts
while( file_exists( $toDirector . $name . $version . $ext )
{
$version++;
}
Will your version handle a filename with other ‘_’s in it.. e.g. my_broken_filename_with_too_many_underscores.jpg?
2. pimaster | August 3rd, 2006 at 4:15 pm
I think so. Didn’t get around to testing it. If I wrote it in java I would have included JUnit tests.
Have they come out with PUnit framework yet?
I only used substrings because I thought it would have made it shorter.
I was thinking of using a regular expression, but my mind was wandering
implode vs substring could be personal. I was thinking that substring might be quicker. (But I might be splitting hairs)
No comments:
Post a Comment