'Unable to Rename the latest file in a folder with PHP

I want to rename the latest added file from a folder, but somehow my code isn't working. Could please help!

For example, if the latest file is "file_0202.json" And I want to Change it to "file.json"

Here is my Code

<?php

$files = scandir('content/myfiles', SCANDIR_SORT_DESCENDING);
$selected_file = $files[0];

$new_filename = preg_replace('/_[^_.]*\./', '.', $selected_file);

if(rename($selected_file, $new_filename, ))
{
echo 'renamed';
}
else {
echo 'can not rename';
}

?>


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source