How can the str_replace function be used effectively to rename files in PHP?

When renaming files in PHP, the str_replace function can be used effectively to replace a specific substring within a file name with another substring. This can be useful when you want to rename multiple files by replacing a common part of their names with a new value.

// Example code to rename files using str_replace function
$directory = 'path/to/files/';
$old_string = 'old_name';
$new_string = 'new_name';

$files = scandir($directory);

foreach($files as $file){
    if($file != '.' && $file != '..'){
        $new_file = str_replace($old_string, $new_string, $file);
        rename($directory . $file, $directory . $new_file);
    }
}