Skip to content

Instantly share code, notes, and snippets.

@dingo-d
Created December 12, 2024 09:51
Show Gist options
  • Save dingo-d/2d0f5a2556a842cdccd24b762e9d7b29 to your computer and use it in GitHub Desktop.
Save dingo-d/2d0f5a2556a842cdccd24b762e9d7b29 to your computer and use it in GitHub Desktop.
Rename svg files
<?php
// Open the current directory
$dir = opendir('.');
// Array to keep track of base filenames
$baseNames = [];
// Loop through all files in the directory
while (($file = readdir($dir)) !== false) {
// Check if the file is an SVG file
if (pathinfo($file, PATHINFO_EXTENSION) === 'svg') {
// Check if the file size is zero bytes
if (filesize($file) === 0) {
// Delete the file if it is zero bytes
unlink($file);
continue;
}
// Convert the filename to lowercase
$newName = strtolower($file);
// Replace spaces with dashes
$newName = str_replace(' ', '-', $newName);
// Replace & with 'and'
$newName = str_replace('&', 'and', $newName);
// Replace special characters with a dash, but preserve the dot before the extension
$newName = preg_replace('/[^a-z0-9\-.]/', '-', $newName);
// Replace multiple dashes with a single dash
$newName = preg_replace('/-+/', '-', $newName);
// Remove trailing dash
$newName = rtrim($newName, '-');
// Extract the base name (without -1, -2, etc.)
$baseName = preg_replace('/-\d+/', '', pathinfo($newName, PATHINFO_FILENAME));
// Check if the base name is already in the array
if (isset($baseNames[$baseName])) {
// If the base name exists, delete the current file
unlink($file);
} else {
// Rename the file
rename($file, $newName);
// Add the base name to the array
$baseNames[$baseName] = true;
}
// Remove -1 suffix if it exists
$newName = preg_replace('/-\d+$/', '', $newName);
}
}
// Close the directory
closedir($dir);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment