Skip to content

Instantly share code, notes, and snippets.

@marydn
Last active June 25, 2017 17:41
Show Gist options
  • Save marydn/10956980 to your computer and use it in GitHub Desktop.
Save marydn/10956980 to your computer and use it in GitHub Desktop.
Clean the name for a file and avoid rewrite files when they are being uploaded to server. Rename it by adding a sequential number at the end of name, before extension.
<?php
// Just keep letters and numbers.
// Replace everything else with dash, even spaces.
//------------------------------------------------------------------------------
$path = dirname(__FILE__);
$file = 'Dos elefantes.mp4'; // Already exists in server
$filename = substr($file, 0, strrpos($file, '.'));
$extension = substr($file, strrpos($file, '.'));
$filename = strtolower(preg_replace('/[^[:alnum:]]/', '-', $filename)) . $extension;
while(is_file($path . $filename)) {
$filename = preg_replace_callback(
'/(?:(?:-([\d]+))?(\.[^.]+))?$/',
function ($match) {
$index = isset($match[1]) ? intval($match[1]) + 1 : 1;
$ext = isset($match[2]) ? $match[2] : '';
return '-' . str_pad($index, 2, '0', STR_PAD_LEFT) . $ext;
},
$filename, 1
);
}
// Result
echo $filename; // dos-elefantes-01.mp4
// If you try upload the same file
echo $filename; // dos-elefantes-02.mp4
<?php
// Just keep letters, numbers and spaces.
// Remove everything else.
//------------------------------------------------------------------------------
$path = dirname(__FILE__);
$file = 'Dos elefantes.mp4'; // Already exists in server
$filename = substr($file, 0, strrpos($file, '.'));
$extension = substr($file, strrpos($file, '.'));
$filename = preg_replace('/[^[:alnum:] ]/', '', $filename) . $extension;
while(is_file($path . $filename)) {
$filename = preg_replace_callback(
'/(?:(?: \(([\d]+)\))?(\.[^.]+))?$/',
function ($match) {
$index = isset($match[1]) ? intval($match[1]) + 1 : 1;
$ext = isset($match[2]) ? $match[2] : '';
return ' ('.$index.')' . $ext;
},
$filename, 1
);
}
// Result
echo $filename; // Dos elefantes (1).mp4
// If you try upload the same file again, will going to be renamed again
echo $filename; // Dos elefantes (2).mp4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment