How can PHP's DirectoryIterator and glob() functions be utilized to rename multiple files at once?
To rename multiple files at once using PHP's DirectoryIterator and glob() functions, you can iterate over the files in a directory using DirectoryIterator, check if they match a specific pattern using glob(), and then rename them accordingly.
$directory = 'path/to/directory/';
$pattern = '*.txt';
$replacement = '_new';
$files = new DirectoryIterator($directory);
foreach ($files as $file) {
if ($file->isFile() && fnmatch($pattern, $file->getFilename())) {
$newName = str_replace($pattern, $replacement, $file->getFilename());
rename($file->getPathname(), $directory . $newName);
}
}
Keywords
Related Questions
- What is the issue with the if-condition in the PHP code provided for hiding a form?
- When dealing with PHP-generated graphics or dynamic content, should this logic be considered part of the View or treated as a separate component in MVC architecture?
- How can the PHP code be optimized to handle unsupported characters or unexpected input when encoding and decoding passwords using the provided character map?