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);
}
}
Keywords
Related Questions
- How can the functions "file_get_contents()" and "file_put_contents()" be used as alternatives to the provided PHP code for file manipulation?
- What are the drawbacks of using easily reversible encryption methods like the one described in the forum thread?
- What are some best practices for handling numeric values received via POST or GET requests in PHP?